Drupal investigation

DateValidator.php 2.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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\Validator\Context\ExecutionContextInterface;
  12. use Symfony\Component\Validator\Constraint;
  13. use Symfony\Component\Validator\ConstraintValidator;
  14. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  15. /**
  16. * @author Bernhard Schussek <bschussek@gmail.com>
  17. */
  18. class DateValidator extends ConstraintValidator
  19. {
  20. const PATTERN = '/^(\d{4})-(\d{2})-(\d{2})$/';
  21. /**
  22. * Checks whether a date is valid.
  23. *
  24. * @param int $year The year
  25. * @param int $month The month
  26. * @param int $day The day
  27. *
  28. * @return bool Whether the date is valid
  29. *
  30. * @internal
  31. */
  32. public static function checkDate($year, $month, $day)
  33. {
  34. return checkdate($month, $day, $year);
  35. }
  36. /**
  37. * {@inheritdoc}
  38. */
  39. public function validate($value, Constraint $constraint)
  40. {
  41. if (!$constraint instanceof Date) {
  42. throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Date');
  43. }
  44. if (null === $value || '' === $value || $value instanceof \DateTime) {
  45. return;
  46. }
  47. if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
  48. throw new UnexpectedTypeException($value, 'string');
  49. }
  50. $value = (string) $value;
  51. if (!preg_match(static::PATTERN, $value, $matches)) {
  52. if ($this->context instanceof ExecutionContextInterface) {
  53. $this->context->buildViolation($constraint->message)
  54. ->setParameter('{{ value }}', $this->formatValue($value))
  55. ->setCode(Date::INVALID_FORMAT_ERROR)
  56. ->addViolation();
  57. } else {
  58. $this->buildViolation($constraint->message)
  59. ->setParameter('{{ value }}', $this->formatValue($value))
  60. ->setCode(Date::INVALID_FORMAT_ERROR)
  61. ->addViolation();
  62. }
  63. return;
  64. }
  65. if (!self::checkDate($matches[1], $matches[2], $matches[3])) {
  66. if ($this->context instanceof ExecutionContextInterface) {
  67. $this->context->buildViolation($constraint->message)
  68. ->setParameter('{{ value }}', $this->formatValue($value))
  69. ->setCode(Date::INVALID_DATE_ERROR)
  70. ->addViolation();
  71. } else {
  72. $this->buildViolation($constraint->message)
  73. ->setParameter('{{ value }}', $this->formatValue($value))
  74. ->setCode(Date::INVALID_DATE_ERROR)
  75. ->addViolation();
  76. }
  77. }
  78. }
  79. }