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 if (null !== $constraint->callback && null !== $constraint->methods) {
36 throw new ConstraintDefinitionException(
37 'The Callback constraint supports either the option "callback" '.
38 'or "methods", but not both at the same time.'
42 // has to be an array so that we can differentiate between callables
44 if (null !== $constraint->methods && !is_array($constraint->methods)) {
45 throw new UnexpectedTypeException($constraint->methods, 'array');
48 $methods = $constraint->methods ?: array($constraint->callback);
50 foreach ($methods as $method) {
51 if ($method instanceof \Closure) {
52 $method($object, $this->context);
53 } elseif (is_array($method)) {
54 if (!is_callable($method)) {
55 if (isset($method[0]) && is_object($method[0])) {
56 $method[0] = get_class($method[0]);
58 throw new ConstraintDefinitionException(sprintf('%s targeted by Callback constraint is not a valid callable', json_encode($method)));
61 call_user_func($method, $object, $this->context);
62 } elseif (null !== $object) {
63 if (!method_exists($object, $method)) {
64 throw new ConstraintDefinitionException(sprintf('Method "%s" targeted by Callback constraint does not exist in class %s', $method, get_class($object)));
67 $reflMethod = new \ReflectionMethod($object, $method);
69 if ($reflMethod->isStatic()) {
70 $reflMethod->invoke(null, $object, $this->context);
72 $reflMethod->invoke($object, $this->context);