Last active
December 5, 2017 18:55
-
-
Save xthiago/c88e86db47527c00b00603c2add94aa8 to your computer and use it in GitHub Desktop.
Integrating Value Object validation with custom Constraint of Symfony Validator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types = 1); | |
namespace Xthiago\Infrastructure\Validation\SymfonyValidator\Constraints; | |
use Xthiago\Domain\Model\PhoneNumber\PhoneNumber; | |
use Xthiago\Domain\Model\PhoneNumber\InvalidPhoneNumberException; | |
use Symfony\Component\Validator\Constraint; | |
use Symfony\Component\Validator\ConstraintValidator; | |
class PhoneConstraintValidator extends ConstraintValidator | |
{ | |
/** | |
* {@inheritdoc} | |
*/ | |
public function validate($phoneNumber, Constraint $constraint) : void | |
{ | |
if (null === $phoneNumber) { | |
return; | |
} | |
try { | |
new PhoneNumber($phoneNumber); | |
} catch (InvalidPhoneNumberException $exception) { | |
$this->context | |
->buildViolation($exception->getMessage()) | |
->addViolation(); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types = 1); | |
namespace Xthiago\Domain\Model\PhoneNumber; | |
class PhoneNumber | |
{ | |
const INVALID_PHONE_REGEX = "/[^0-9+ \-()]+/"; | |
/** | |
* @var string | |
*/ | |
protected $phoneNumber; | |
/** | |
* PhoneNumber constructor. | |
* | |
* @param string $phoneNumber | |
*/ | |
public function __construct(string $phoneNumber) | |
{ | |
if (empty($phoneNumber)) { | |
throw InvalidPhoneNumberException::createForEmptyValue(); | |
} | |
$phoneRegexResult = preg_match(self::INVALID_PHONE_REGEX, $phoneNumber); | |
if (1 === $phoneRegexResult) { | |
throw InvalidPhoneNumberException::createForInvalidValue($phoneNumber); | |
} | |
$this->phoneNumber = $phoneNumber; | |
} | |
/** | |
* @return string | |
*/ | |
public function __toString() | |
{ | |
return $this->phoneNumber; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment