4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Validator\Constraints;
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;
20 * Validator for Callback constraint.
22 * @author Bernhard Schussek <bschussek@gmail.com>
24 class CallbackValidator extends ConstraintValidator
29 public function validate($object, Constraint $constraint)
31 if (!$constraint instanceof Callback) {
32 throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Callback');
35 $method = $constraint->callback;
36 if ($method instanceof \Closure) {
37 $method($object, $this->context, $constraint->payload);
38 } elseif (\is_array($method)) {
39 if (!\is_callable($method)) {
40 if (isset($method[0]) && \is_object($method[0])) {
41 $method[0] = \get_class($method[0]);
43 throw new ConstraintDefinitionException(sprintf('%s targeted by Callback constraint is not a valid callable', json_encode($method)));
46 \call_user_func($method, $object, $this->context, $constraint->payload);
47 } elseif (null !== $object) {
48 if (!method_exists($object, $method)) {
49 throw new ConstraintDefinitionException(sprintf('Method "%s" targeted by Callback constraint does not exist in class %s', $method, \get_class($object)));
52 $reflMethod = new \ReflectionMethod($object, $method);
54 if ($reflMethod->isStatic()) {
55 $reflMethod->invoke(null, $object, $this->context, $constraint->payload);
57 $reflMethod->invoke($object, $this->context, $constraint->payload);