Skip to content

Instantly share code, notes, and snippets.

@xthiago
Last active December 5, 2017 18:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xthiago/c88e86db47527c00b00603c2add94aa8 to your computer and use it in GitHub Desktop.
Save xthiago/c88e86db47527c00b00603c2add94aa8 to your computer and use it in GitHub Desktop.
Integrating Value Object validation with custom Constraint of Symfony Validator
<?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();
}
}
}
<?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