1: <?php
2: /**
3: * Wei Framework
4: *
5: * @copyright Copyright (c) 2008-2013 Twin Huang
6: * @license http://opensource.org/licenses/mit-license.php MIT License
7: */
8:
9: namespace Wei\Validator;
10:
11: /**
12: * Check if the input is valid by specified callback
13: *
14: * @author Twin Huang <twinhuang@qq.com>
15: */
16: class Callback extends BaseValidator
17: {
18: protected $invalidMessage = '%name% is not valid';
19:
20: /**
21: * The callback to validate the input
22: *
23: * @var callback
24: */
25: protected $fn;
26:
27: /**
28: * Check if the input is valid by specified callback
29: *
30: * @param mixed $input The input value
31: * @param \Closure|null $fn The callback to validate the input
32: * @param string|null $message The custom invalid message
33: * @return bool
34: */
35: public function __invoke($input, \Closure $fn = null, $message = null)
36: {
37: $fn && $this->storeOption('fn', $fn);
38: $message && $this->storeOption('message', $message);
39:
40: return $this->isValid($input);
41: }
42:
43: /**
44: * {@inheritdoc}
45: */
46: protected function doValidate($input)
47: {
48: if (!call_user_func($this->fn, $input, $this, $this->wei)) {
49: $this->addError('invalid');
50: return false;
51: }
52: return true;
53: }
54:
55: /**
56: * Set the invalid message
57: *
58: * @param string $message
59: * @return $this
60: */
61: public function setMessage($message)
62: {
63: $this->message = $message;
64: return $this;
65: }
66: }
67: