CallbackValidator.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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\ConstraintDefinitionException;
  14. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  15. /**
  16. * Validator for Callback constraint.
  17. *
  18. * @author Bernhard Schussek <bschussek@gmail.com>
  19. */
  20. class CallbackValidator extends ConstraintValidator
  21. {
  22. /**
  23. * {@inheritdoc}
  24. */
  25. public function validate($object, Constraint $constraint)
  26. {
  27. if (!$constraint instanceof Callback) {
  28. throw new UnexpectedTypeException($constraint, Callback::class);
  29. }
  30. $method = $constraint->callback;
  31. if ($method instanceof \Closure) {
  32. $method($object, $this->context, $constraint->payload);
  33. } elseif (\is_array($method)) {
  34. if (!\is_callable($method)) {
  35. if (isset($method[0]) && \is_object($method[0])) {
  36. $method[0] = \get_class($method[0]);
  37. }
  38. throw new ConstraintDefinitionException(json_encode($method).' targeted by Callback constraint is not a valid callable.');
  39. }
  40. $method($object, $this->context, $constraint->payload);
  41. } elseif (null !== $object) {
  42. if (!method_exists($object, $method)) {
  43. throw new ConstraintDefinitionException(sprintf('Method "%s" targeted by Callback constraint does not exist in class "%s".', $method, get_debug_type($object)));
  44. }
  45. $reflMethod = new \ReflectionMethod($object, $method);
  46. if ($reflMethod->isStatic()) {
  47. $reflMethod->invoke(null, $object, $this->context, $constraint->payload);
  48. } else {
  49. $reflMethod->invoke($object, $this->context, $constraint->payload);
  50. }
  51. }
  52. }
  53. }