You are here

public function AbstractComparisonValidator::validate in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 vendor/symfony/validator/Constraints/AbstractComparisonValidator.php \Symfony\Component\Validator\Constraints\AbstractComparisonValidator::validate()

Checks if the passed value is valid.

Parameters

mixed $value The value that should be validated:

Constraint $constraint The constraint for the validation:

Overrides ConstraintValidatorInterface::validate

File

vendor/symfony/validator/Constraints/AbstractComparisonValidator.php, line 30

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)) {
    if ($this->context instanceof ExecutionContextInterface) {
      $this->context
        ->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();
    }
    else {
      $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();
    }
  }
}