From 6f67fe5458d6c645b5c951b666d25c6449b003f9 Mon Sep 17 00:00:00 2001 From: Hirofumi Tanigami Date: Tue, 6 Nov 2018 12:03:19 +0900 Subject: [PATCH] soft validate email address --- src/Web/EmailAddress.php | 26 +++++++++++++++++++++++--- tests/Web/EmailAddressTest.php | 23 +++++++++++++++++++++-- 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/src/Web/EmailAddress.php b/src/Web/EmailAddress.php index 5463c2b..46f55a2 100644 --- a/src/Web/EmailAddress.php +++ b/src/Web/EmailAddress.php @@ -13,13 +13,15 @@ class EmailAddress /** * @param string $emailAddress + * @param bool $validateSoft */ - public function __construct(string $emailAddress) + public function __construct(string $emailAddress, bool $validateSoft = false) { - if (false === filter_var($emailAddress, FILTER_VALIDATE_EMAIL)) { + if ($validateSoft && !$this->validateSoft($emailAddress) || + !$validateSoft && !$this->validateStrict($emailAddress) + ) { throw new InvalidArgumentException(sprintf('Invalid email address: %s', $emailAddress)); } - $this->emailAddress = $emailAddress; } @@ -39,4 +41,22 @@ public function emailAddress(): string { return $this->emailAddress; } + + /** + * @param string $emailAddress + * @return bool + */ + private function validateSoft(string $emailAddress): bool + { + return preg_match('/^.+\@\S+\.\S+$/', $emailAddress); + } + + /** + * @param string $emailAddress + * @return bool + */ + private function validateStrict(string $emailAddress): bool + { + return filter_var($emailAddress, FILTER_VALIDATE_EMAIL); + } } diff --git a/tests/Web/EmailAddressTest.php b/tests/Web/EmailAddressTest.php index 134e98e..95d7ade 100644 --- a/tests/Web/EmailAddressTest.php +++ b/tests/Web/EmailAddressTest.php @@ -8,13 +8,32 @@ class EmailAddressTest extends TestCase { /** * @expectedException \InvalidArgumentException - * @expectedMessage nvalid email address: this_is_not_email_address + * @expectedMessage Invalid email address: this_is_not_email_address */ - public function testConstructorReturnsExceptionIfUrlIsInvalid() + public function testConstructorThrowsExceptionIfUrlIsInvalid() { new EmailAddress('this_is_not_email_address'); } + /** + * @expectedException \InvalidArgumentException + * @expectedMessage Invalid email address: email..@example.com' + */ + public function testConstructorValidatesStrict() + { + new EmailAddress('email..@example.com'); + } + + /** + * @expectedException \InvalidArgumentException + * @expectedMessage Invalid email address: this_is_not_email_address + */ + public function testConstructorValidatesSoft() + { + new EmailAddress('email..@example.com', true); + new EmailAddress('this_is_not_email_address', true); + } + public function testGetterReturnsValueString() { $this->assertSame('tanigami@gmail.com', (new EmailAddress('tanigami@gmail.com'))->emailAddress());