UlidValidator.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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\Constraint;
  12. use Symfony\Component\Validator\ConstraintValidator;
  13. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  14. use Symfony\Component\Validator\Exception\UnexpectedValueException;
  15. /**
  16. * Validates whether the value is a valid ULID (Universally Unique Lexicographically Sortable Identifier).
  17. * Cf https://github.com/ulid/spec for ULID specifications.
  18. *
  19. * @author Laurent Clouet <laurent35240@gmail.com>
  20. */
  21. class UlidValidator extends ConstraintValidator
  22. {
  23. /**
  24. * {@inheritdoc}
  25. */
  26. public function validate($value, Constraint $constraint)
  27. {
  28. if (!$constraint instanceof Ulid) {
  29. throw new UnexpectedTypeException($constraint, Ulid::class);
  30. }
  31. if (null === $value || '' === $value) {
  32. return;
  33. }
  34. if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) {
  35. throw new UnexpectedValueException($value, 'string');
  36. }
  37. $value = (string) $value;
  38. if (26 !== \strlen($value)) {
  39. $this->context->buildViolation($constraint->message)
  40. ->setParameter('{{ value }}', $this->formatValue($value))
  41. ->setCode(26 > \strlen($value) ? Ulid::TOO_SHORT_ERROR : Ulid::TOO_LONG_ERROR)
  42. ->addViolation();
  43. }
  44. if (\strlen($value) !== strspn($value, '0123456789ABCDEFGHJKMNPQRSTVWXYZabcdefghjkmnpqrstvwxyz')) {
  45. $this->context->buildViolation($constraint->message)
  46. ->setParameter('{{ value }}', $this->formatValue($value))
  47. ->setCode(Ulid::INVALID_CHARACTERS_ERROR)
  48. ->addViolation();
  49. }
  50. // Largest valid ULID is '7ZZZZZZZZZZZZZZZZZZZZZZZZZ'
  51. // Cf https://github.com/ulid/spec#overflow-errors-when-parsing-base32-strings
  52. if ($value[0] > '7') {
  53. $this->context->buildViolation($constraint->message)
  54. ->setParameter('{{ value }}', $this->formatValue($value))
  55. ->setCode(Ulid::TOO_LARGE_ERROR)
  56. ->addViolation();
  57. }
  58. }
  59. }