RangeValidator.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Validator\Constraints;
  11. use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException;
  12. use Symfony\Component\PropertyAccess\PropertyAccess;
  13. use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
  14. use Symfony\Component\Validator\Constraint;
  15. use Symfony\Component\Validator\ConstraintValidator;
  16. use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
  17. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  18. /**
  19. * @author Bernhard Schussek <bschussek@gmail.com>
  20. */
  21. class RangeValidator extends ConstraintValidator
  22. {
  23. private $propertyAccessor;
  24. public function __construct(PropertyAccessorInterface $propertyAccessor = null)
  25. {
  26. $this->propertyAccessor = $propertyAccessor;
  27. }
  28. /**
  29. * {@inheritdoc}
  30. */
  31. public function validate($value, Constraint $constraint)
  32. {
  33. if (!$constraint instanceof Range) {
  34. throw new UnexpectedTypeException($constraint, Range::class);
  35. }
  36. if (null === $value) {
  37. return;
  38. }
  39. $min = $this->getLimit($constraint->minPropertyPath, $constraint->min, $constraint);
  40. $max = $this->getLimit($constraint->maxPropertyPath, $constraint->max, $constraint);
  41. if (!is_numeric($value) && !$value instanceof \DateTimeInterface) {
  42. if ($this->isParsableDatetimeString($min) && $this->isParsableDatetimeString($max)) {
  43. $this->context->buildViolation($constraint->invalidDateTimeMessage)
  44. ->setParameter('{{ value }}', $this->formatValue($value, self::PRETTY_DATE))
  45. ->setCode(Range::INVALID_CHARACTERS_ERROR)
  46. ->addViolation();
  47. } else {
  48. $this->context->buildViolation($constraint->invalidMessage)
  49. ->setParameter('{{ value }}', $this->formatValue($value, self::PRETTY_DATE))
  50. ->setCode(Range::INVALID_CHARACTERS_ERROR)
  51. ->addViolation();
  52. }
  53. return;
  54. }
  55. // Convert strings to DateTimes if comparing another DateTime
  56. // This allows to compare with any date/time value supported by
  57. // the DateTime constructor:
  58. // https://php.net/datetime.formats
  59. if ($value instanceof \DateTimeInterface) {
  60. $dateTimeClass = null;
  61. if (\is_string($min)) {
  62. $dateTimeClass = $value instanceof \DateTimeImmutable ? \DateTimeImmutable::class : \DateTime::class;
  63. try {
  64. $min = new $dateTimeClass($min);
  65. } catch (\Exception $e) {
  66. throw new ConstraintDefinitionException(sprintf('The min value "%s" could not be converted to a "%s" instance in the "%s" constraint.', $min, $dateTimeClass, get_debug_type($constraint)));
  67. }
  68. }
  69. if (\is_string($max)) {
  70. $dateTimeClass = $dateTimeClass ?: ($value instanceof \DateTimeImmutable ? \DateTimeImmutable::class : \DateTime::class);
  71. try {
  72. $max = new $dateTimeClass($max);
  73. } catch (\Exception $e) {
  74. throw new ConstraintDefinitionException(sprintf('The max value "%s" could not be converted to a "%s" instance in the "%s" constraint.', $max, $dateTimeClass, get_debug_type($constraint)));
  75. }
  76. }
  77. }
  78. $hasLowerLimit = null !== $min;
  79. $hasUpperLimit = null !== $max;
  80. if ($hasLowerLimit && $hasUpperLimit && ($value < $min || $value > $max)) {
  81. $message = $constraint->notInRangeMessage;
  82. $code = Range::NOT_IN_RANGE_ERROR;
  83. if ($value < $min && $constraint->deprecatedMinMessageSet) {
  84. $message = $constraint->minMessage;
  85. $code = Range::TOO_LOW_ERROR;
  86. }
  87. if ($value > $max && $constraint->deprecatedMaxMessageSet) {
  88. $message = $constraint->maxMessage;
  89. $code = Range::TOO_HIGH_ERROR;
  90. }
  91. $violationBuilder = $this->context->buildViolation($message)
  92. ->setParameter('{{ value }}', $this->formatValue($value, self::PRETTY_DATE))
  93. ->setParameter('{{ min }}', $this->formatValue($min, self::PRETTY_DATE))
  94. ->setParameter('{{ max }}', $this->formatValue($max, self::PRETTY_DATE))
  95. ->setCode($code);
  96. if (null !== $constraint->maxPropertyPath) {
  97. $violationBuilder->setParameter('{{ max_limit_path }}', $constraint->maxPropertyPath);
  98. }
  99. if (null !== $constraint->minPropertyPath) {
  100. $violationBuilder->setParameter('{{ min_limit_path }}', $constraint->minPropertyPath);
  101. }
  102. $violationBuilder->addViolation();
  103. return;
  104. }
  105. if ($hasUpperLimit && $value > $max) {
  106. $violationBuilder = $this->context->buildViolation($constraint->maxMessage)
  107. ->setParameter('{{ value }}', $this->formatValue($value, self::PRETTY_DATE))
  108. ->setParameter('{{ limit }}', $this->formatValue($max, self::PRETTY_DATE))
  109. ->setCode(Range::TOO_HIGH_ERROR);
  110. if (null !== $constraint->maxPropertyPath) {
  111. $violationBuilder->setParameter('{{ max_limit_path }}', $constraint->maxPropertyPath);
  112. }
  113. if (null !== $constraint->minPropertyPath) {
  114. $violationBuilder->setParameter('{{ min_limit_path }}', $constraint->minPropertyPath);
  115. }
  116. $violationBuilder->addViolation();
  117. return;
  118. }
  119. if ($hasLowerLimit && $value < $min) {
  120. $violationBuilder = $this->context->buildViolation($constraint->minMessage)
  121. ->setParameter('{{ value }}', $this->formatValue($value, self::PRETTY_DATE))
  122. ->setParameter('{{ limit }}', $this->formatValue($min, self::PRETTY_DATE))
  123. ->setCode(Range::TOO_LOW_ERROR);
  124. if (null !== $constraint->maxPropertyPath) {
  125. $violationBuilder->setParameter('{{ max_limit_path }}', $constraint->maxPropertyPath);
  126. }
  127. if (null !== $constraint->minPropertyPath) {
  128. $violationBuilder->setParameter('{{ min_limit_path }}', $constraint->minPropertyPath);
  129. }
  130. $violationBuilder->addViolation();
  131. }
  132. }
  133. private function getLimit($propertyPath, $default, Constraint $constraint)
  134. {
  135. if (null === $propertyPath) {
  136. return $default;
  137. }
  138. if (null === $object = $this->context->getObject()) {
  139. return $default;
  140. }
  141. try {
  142. return $this->getPropertyAccessor()->getValue($object, $propertyPath);
  143. } catch (NoSuchPropertyException $e) {
  144. throw new ConstraintDefinitionException(sprintf('Invalid property path "%s" provided to "%s" constraint: ', $propertyPath, get_debug_type($constraint)).$e->getMessage(), 0, $e);
  145. }
  146. }
  147. private function getPropertyAccessor(): PropertyAccessorInterface
  148. {
  149. if (null === $this->propertyAccessor) {
  150. $this->propertyAccessor = PropertyAccess::createPropertyAccessor();
  151. }
  152. return $this->propertyAccessor;
  153. }
  154. private function isParsableDatetimeString($boundary): bool
  155. {
  156. if (null === $boundary) {
  157. return true;
  158. }
  159. if (!\is_string($boundary)) {
  160. return false;
  161. }
  162. try {
  163. new \DateTime($boundary);
  164. } catch (\Exception $e) {
  165. return false;
  166. }
  167. return true;
  168. }
  169. }