3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
10 namespace Zend\Validator
;
12 class Callback
extends AbstractValidator
17 const INVALID_CALLBACK
= 'callbackInvalid';
22 const INVALID_VALUE
= 'callbackValue';
25 * Validation failure message template definitions
29 protected $messageTemplates = array(
30 self
::INVALID_VALUE
=> "The input is not valid",
31 self
::INVALID_CALLBACK
=> "An exception has been raised within the callback",
35 * Default options to set for the validator
39 protected $options = array(
40 'callback' => null, // Callback in a call_user_func format, string || array
41 'callbackOptions' => array(), // Options for the callback
47 * @param array|callable $options
49 public function __construct($options = null)
51 if (is_callable($options)) {
52 $options = array('callback' => $options);
55 parent
::__construct($options);
59 * Returns the set callback
63 public function getCallback()
65 return $this->options
['callback'];
71 * @param string|array|callable $callback
72 * @return Callback Provides a fluent interface
73 * @throws Exception\InvalidArgumentException
75 public function setCallback($callback)
77 if (!is_callable($callback)) {
78 throw new Exception\
InvalidArgumentException('Invalid callback given');
81 $this->options
['callback'] = $callback;
86 * Returns the set options for the callback
90 public function getCallbackOptions()
92 return $this->options
['callbackOptions'];
96 * Sets options for the callback
98 * @param mixed $options
99 * @return Callback Provides a fluent interface
101 public function setCallbackOptions($options)
103 $this->options
['callbackOptions'] = (array) $options;
108 * Returns true if and only if the set callback returns
109 * for the provided $value
111 * @param mixed $value
112 * @param mixed $context Additional context to provide to the callback
114 * @throws Exception\InvalidArgumentException
116 public function isValid($value, $context = null)
118 $this->setValue($value);
120 $options = $this->getCallbackOptions();
121 $callback = $this->getCallback();
122 if (empty($callback)) {
123 throw new Exception\
InvalidArgumentException('No callback given');
126 $args = array($value);
127 if (empty($options) && !empty($context)) {
130 if (!empty($options) && empty($context)) {
131 $args = array_merge($args, $options);
133 if (!empty($options) && !empty($context)) {
135 $args = array_merge($args, $options);
139 if (!call_user_func_array($callback, $args)) {
140 $this->error(self
::INVALID_VALUE
);
143 } catch (\Exception
$e) {
144 $this->error(self
::INVALID_CALLBACK
);