Skip to content

Commit 6f67fe5

Browse files
committed
soft validate email address
1 parent 4b73640 commit 6f67fe5

2 files changed

Lines changed: 44 additions & 5 deletions

File tree

src/Web/EmailAddress.php

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,15 @@ class EmailAddress
1313

1414
/**
1515
* @param string $emailAddress
16+
* @param bool $validateSoft
1617
*/
17-
public function __construct(string $emailAddress)
18+
public function __construct(string $emailAddress, bool $validateSoft = false)
1819
{
19-
if (false === filter_var($emailAddress, FILTER_VALIDATE_EMAIL)) {
20+
if ($validateSoft && !$this->validateSoft($emailAddress) ||
21+
!$validateSoft && !$this->validateStrict($emailAddress)
22+
) {
2023
throw new InvalidArgumentException(sprintf('Invalid email address: %s', $emailAddress));
2124
}
22-
2325
$this->emailAddress = $emailAddress;
2426
}
2527

@@ -39,4 +41,22 @@ public function emailAddress(): string
3941
{
4042
return $this->emailAddress;
4143
}
44+
45+
/**
46+
* @param string $emailAddress
47+
* @return bool
48+
*/
49+
private function validateSoft(string $emailAddress): bool
50+
{
51+
return preg_match('/^.+\@\S+\.\S+$/', $emailAddress);
52+
}
53+
54+
/**
55+
* @param string $emailAddress
56+
* @return bool
57+
*/
58+
private function validateStrict(string $emailAddress): bool
59+
{
60+
return filter_var($emailAddress, FILTER_VALIDATE_EMAIL);
61+
}
4262
}

tests/Web/EmailAddressTest.php

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,32 @@ class EmailAddressTest extends TestCase
88
{
99
/**
1010
* @expectedException \InvalidArgumentException
11-
* @expectedMessage nvalid email address: this_is_not_email_address
11+
* @expectedMessage Invalid email address: this_is_not_email_address
1212
*/
13-
public function testConstructorReturnsExceptionIfUrlIsInvalid()
13+
public function testConstructorThrowsExceptionIfUrlIsInvalid()
1414
{
1515
new EmailAddress('this_is_not_email_address');
1616
}
1717

18+
/**
19+
* @expectedException \InvalidArgumentException
20+
* @expectedMessage Invalid email address: email..@example.com'
21+
*/
22+
public function testConstructorValidatesStrict()
23+
{
24+
new EmailAddress('email..@example.com');
25+
}
26+
27+
/**
28+
* @expectedException \InvalidArgumentException
29+
* @expectedMessage Invalid email address: this_is_not_email_address
30+
*/
31+
public function testConstructorValidatesSoft()
32+
{
33+
new EmailAddress('email..@example.com', true);
34+
new EmailAddress('this_is_not_email_address', true);
35+
}
36+
1837
public function testGetterReturnsValueString()
1938
{
2039
$this->assertSame('tanigami@gmail.com', (new EmailAddress('tanigami@gmail.com'))->emailAddress());

0 commit comments

Comments
 (0)