JsonValidator.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. /**
  15. * @author Imad ZAIRIG <imadzairig@gmail.com>
  16. */
  17. class JsonValidator extends ConstraintValidator
  18. {
  19. /**
  20. * {@inheritdoc}
  21. */
  22. public function validate($value, Constraint $constraint)
  23. {
  24. if (!$constraint instanceof Json) {
  25. throw new UnexpectedTypeException($constraint, Json::class);
  26. }
  27. if (null === $value || '' === $value) {
  28. return;
  29. }
  30. if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) {
  31. throw new UnexpectedTypeException($value, 'string');
  32. }
  33. $value = (string) $value;
  34. json_decode($value);
  35. if (\JSON_ERROR_NONE !== json_last_error()) {
  36. $this->context->buildViolation($constraint->message)
  37. ->setParameter('{{ value }}', $this->formatValue($value))
  38. ->setCode(Json::INVALID_JSON_ERROR)
  39. ->addViolation();
  40. }
  41. }
  42. }