Skip to content

Commit

Permalink
soft validate email address
Browse files Browse the repository at this point in the history
  • Loading branch information
tanigami committed Nov 6, 2018
1 parent 4b73640 commit 6f67fe5
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 5 deletions.
26 changes: 23 additions & 3 deletions src/Web/EmailAddress.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand All @@ -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);
}
}
23 changes: 21 additions & 2 deletions tests/Web/EmailAddressTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 protected]'
*/
public function testConstructorValidatesStrict()
{
new EmailAddress('[email protected]');
}

/**
* @expectedException \InvalidArgumentException
* @expectedMessage Invalid email address: this_is_not_email_address
*/
public function testConstructorValidatesSoft()
{
new EmailAddress('[email protected]', true);
new EmailAddress('this_is_not_email_address', true);
}

public function testGetterReturnsValueString()
{
$this->assertSame('[email protected]', (new EmailAddress('[email protected]'))->emailAddress());
Expand Down

0 comments on commit 6f67fe5

Please sign in to comment.