1: <?php
2: /**
3: * Wei Framework
4: *
5: * @copyright Copyright (c) 2008-2015 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 type of input is equals specified type name
13: *
14: * @author Twin Huang <twinhuang@qq.com>
15: */
16: class Type extends BaseValidator
17: {
18: protected $typeMessage = '%name% must be %typeName%';
19:
20: protected $negativeMessage = '%name% must not be %typeName%';
21:
22: /**
23: * The expected type of input
24: *
25: * @var string
26: */
27: protected $type;
28:
29: /**
30: * The translated type name for display
31: *
32: * @var string
33: */
34: protected $typeName;
35:
36: /**
37: * {@inheritdoc}
38: *
39: * @param string $type The expected type of $input
40: */
41: public function __invoke($input, $type = null)
42: {
43: $type && $this->storeOption('type', $type);
44:
45: return $this->isValid($input);
46: }
47:
48: /**
49: * {@inheritdoc}
50: */
51: protected function doValidate($input)
52: {
53: if (function_exists($fn = 'is_' . $this->type)) {
54: $result = $fn($input);
55: } elseif (function_exists($fn = 'ctype_' . $this->type)) {
56: $result = $fn($input);
57: } else {
58: $result = $input instanceof $this->type;
59: }
60:
61: if (!$result) {
62: $this->addError('type');
63: }
64:
65: return $result;
66: }
67:
68: /**
69: * {@inheritdoc}
70: */
71: public function getMessages($name = null)
72: {
73: $this->loadTranslationMessages();
74: $this->typeName = $this->t($this->type);
75: return parent::getMessages($name);
76: }
77: }
78: