Quando se trata de inserir o ddd com menos de dois números, ou inserir o número de fato com menos de 8 números... funciona. Ao testar a inserção no ddd com 3 dígitos ou o telefone com 10... não funciona.
class PhoneTest extends TestCase
{
public function test_invalid_ddd_with_one_digit(): void
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage("DDD inválido.");
new PhoneNumber("3", "987342650");
}
public function test_invalid_ddd_with_three_digits(): void
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage("DDD inválido.");
new PhoneNumber("311", "987342650");
}
public function test_invalid_number_with_seven_numbers(): void
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage("Número inválido.");
new PhoneNumber("33", "9873426");
}
public function test_invalid_number_with_ten_numbers()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage("Número inválido.");
new PhoneNumber("33", "9873426500");
}
}
Phone (Alura\tests\Phone)
✔ Invalid ddd with one digit
✘ Invalid ddd with three digits
┐
├ Failed asserting that exception of type "InvalidArgumentException" is thrown.
┴
✔ Invalid number with seven numbers
✘ Invalid number with ten numbers
┐
├ Failed asserting that exception of type "InvalidArgumentException" is thrown.
┴
Time: 00:00.023, Memory: 4.00 MB
Classe PhoneNumber
class PhoneNumber
{
private string $ddd;
private string $number;
public function __construct(string $ddd, string $number)
{
$this->setDdd($ddd);
$this->setNumber($number);
}
public function setDdd(string $ddd): void
{
if (preg_match('/\d{2}/', $ddd) !== 1) {
throw new \InvalidArgumentException("DDD inválido.");
}
$this->ddd = $ddd;
}
public function setNumber(string $number): void
{
if (preg_match('/\d{8,9}/', $number) !== 1) {
throw new \InvalidArgumentException("Número inválido.");
}
$this->number = $number;
}
public function __toString(): string
{
return "{$this->ddd}{$this->number}";
}
}