From 7e1c8db2743d26af763b8f59c15a97717b501b0a Mon Sep 17 00:00:00 2001 From: Eldad Fux Date: Sun, 19 Oct 2025 21:49:54 +0100 Subject: [PATCH] Add allowEmpty option to Email validator for flexible validation behavior Enhance the Email class by introducing an option to allow empty values during validation. This change includes a constructor parameter to set the allowEmpty flag and updates the validation logic accordingly. Additional tests have been added to verify the behavior with allowEmpty enabled and disabled, ensuring comprehensive coverage of the new functionality. --- src/Emails/Validator/Email.php | 11 +++++++++++ tests/Validator/EmailTest.php | 25 +++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/Emails/Validator/Email.php b/src/Emails/Validator/Email.php index 4bffadc..7ee3ca1 100644 --- a/src/Emails/Validator/Email.php +++ b/src/Emails/Validator/Email.php @@ -12,6 +12,13 @@ */ class Email extends Validator { + protected bool $allowEmpty; + + public function __construct(bool $allowEmpty = false) + { + $this->allowEmpty = $allowEmpty; + } + /** * Get Description * @@ -35,6 +42,10 @@ public function isValid($value): bool return false; } + if ($this->allowEmpty && \strlen($value) === 0) { + return true; + } + try { $email = new EmailParser($value); diff --git a/tests/Validator/EmailTest.php b/tests/Validator/EmailTest.php index f88dfea..a234ef1 100644 --- a/tests/Validator/EmailTest.php +++ b/tests/Validator/EmailTest.php @@ -78,4 +78,29 @@ public function test_validator_is_array(): void $this->assertEquals(false, $validator->isArray()); } + + public function test_allow_empty_disabled(): void + { + $validator = new Email(false); + + $this->assertEquals(false, $validator->isValid('')); + $this->assertEquals(true, $validator->isValid('test@example.com')); + } + + public function test_allow_empty_enabled(): void + { + $validator = new Email(true); + + $this->assertEquals(true, $validator->isValid('')); + $this->assertEquals(true, $validator->isValid('test@example.com')); + $this->assertEquals(false, $validator->isValid('invalid-email')); + } + + public function test_allow_empty_default_behavior(): void + { + $validator = new Email; + + $this->assertEquals(false, $validator->isValid('')); + $this->assertEquals(true, $validator->isValid('test@example.com')); + } }