You are here

public function AbstractComparisonValidator::validate in Plug 7

Checks if the passed value is valid.

@api

Parameters

mixed $value The value that should be validated:

Constraint $constraint The constraint for the validation:

Overrides ConstraintValidatorInterface::validate

File

lib/Symfony/validator/Symfony/Component/Validator/Constraints/AbstractComparisonValidator.php, line 29

Class

AbstractComparisonValidator
Provides a base class for the validation of property comparisons.

Namespace

Symfony\Component\Validator\Constraints

Code

public function validate($value, Constraint $constraint) {
  if (!$constraint instanceof AbstractComparison) {
    throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\\AbstractComparison');
  }
  if (null === $value) {
    return;
  }
  $comparedValue = $constraint->value;

  // Convert strings to DateTimes if comparing another DateTime
  // This allows to compare with any date/time value supported by
  // the DateTime constructor:
  // http://php.net/manual/en/datetime.formats.php
  if (is_string($comparedValue)) {
    if ($value instanceof \DatetimeImmutable) {

      // If $value is immutable, convert the compared value to a
      // DateTimeImmutable too
      $comparedValue = new \DatetimeImmutable($comparedValue);
    }
    elseif ($value instanceof \DateTime || $value instanceof \DateTimeInterface) {

      // Otherwise use DateTime
      $comparedValue = new \DateTime($comparedValue);
    }
  }
  if (!$this
    ->compareValues($value, $comparedValue)) {
    $this
      ->buildViolation($constraint->message)
      ->setParameter('{{ value }}', $this
      ->formatValue($value, self::OBJECT_TO_STRING | self::PRETTY_DATE))
      ->setParameter('{{ compared_value }}', $this
      ->formatValue($comparedValue, self::OBJECT_TO_STRING | self::PRETTY_DATE))
      ->setParameter('{{ compared_value_type }}', $this
      ->formatTypeOf($comparedValue))
      ->addViolation();
  }
}