4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Validator\Constraints;
14 use Symfony\Component\Validator\Constraint;
15 use Symfony\Component\Validator\ConstraintValidator;
16 use Symfony\Component\Validator\Exception\UnexpectedTypeException;
19 * Provides a base class for the validation of property comparisons.
21 * @author Daniel Holmes <daniel@danielholmes.org>
22 * @author Bernhard Schussek <bschussek@gmail.com>
24 abstract class AbstractComparisonValidator extends ConstraintValidator
29 public function validate($value, Constraint $constraint)
31 if (!$constraint instanceof AbstractComparison) {
32 throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\AbstractComparison');
35 if (null === $value) {
39 $comparedValue = $constraint->value;
41 // Convert strings to DateTimes if comparing another DateTime
42 // This allows to compare with any date/time value supported by
43 // the DateTime constructor:
44 // http://php.net/manual/en/datetime.formats.php
45 if (is_string($comparedValue)) {
46 if ($value instanceof \DateTimeImmutable) {
47 // If $value is immutable, convert the compared value to a
48 // DateTimeImmutable too
49 $comparedValue = new \DatetimeImmutable($comparedValue);
50 } elseif ($value instanceof \DateTimeInterface) {
51 // Otherwise use DateTime
52 $comparedValue = new \DateTime($comparedValue);
56 if (!$this->compareValues($value, $comparedValue)) {
57 $this->context->buildViolation($constraint->message)
58 ->setParameter('{{ value }}', $this->formatValue($value, self::OBJECT_TO_STRING | self::PRETTY_DATE))
59 ->setParameter('{{ compared_value }}', $this->formatValue($comparedValue, self::OBJECT_TO_STRING | self::PRETTY_DATE))
60 ->setParameter('{{ compared_value_type }}', $this->formatTypeOf($comparedValue))
61 ->setCode($this->getErrorCode())
67 * Compares the two given values to find if their relationship is valid.
69 * @param mixed $value1 The first value to compare
70 * @param mixed $value2 The second value to compare
72 * @return bool true if the relationship is valid, false otherwise
74 abstract protected function compareValues($value1, $value2);
77 * Returns the error code used if the comparison fails.
79 * @return string|null The error code or `null` if no code should be set
81 protected function getErrorCode()