1: <?php
2: 3: 4: 5: 6: 7:
8:
9: namespace Wei\Validator;
10:
11: 12: 13: 14: 15: 16:
17: class Length extends BaseValidator
18: {
19: protected $notDetectedMessage = '%name%\'s length could not be detected';
20:
21: protected $lengthMessage = '%name% must have a length of %length%';
22:
23: protected $lengthItemMessage = '%name% must contain %length% item(s)';
24:
25: protected $notInMessage = '%name% must have a length between %min% and %max%';
26:
27: protected $notInItemMessage = '%name% must contain %min% to %max% item(s)';
28:
29: protected $min;
30:
31: protected $max;
32:
33: 34: 35: 36: 37:
38: protected $length;
39:
40: 41: 42: 43: 44:
45: protected $countByChars = false;
46:
47: 48: 49: 50: 51:
52: protected $charset = 'UTF-8';
53:
54: 55: 56:
57: public function __invoke($input, $min = null, $max = null)
58: {
59:
60: if (is_numeric($min) && is_numeric($max)) {
61: $this->storeOption('min', $min);
62: $this->storeOption('max', $max);
63:
64: } elseif (is_numeric($min) && is_null($max)) {
65: $this->storeOption('length', $min);
66: }
67:
68: return $this->isValid($input);
69: }
70:
71: 72: 73:
74: protected function doValidate($input)
75: {
76: if (false === ($len = $this->getLength($input))) {
77: $this->addError('notDetected');
78: return false;
79: }
80:
81: if (!is_null($this->length)) {
82: if ($this->length != $len) {
83: $this->addError(is_scalar($input) ? 'length' : 'lengthItem');
84: return false;
85: }
86: } elseif ($this->min > $len || $this->max < $len) {
87: $this->addError(is_scalar($input) ? 'notIn' : 'notInItem');
88: return false;
89: }
90:
91: return true;
92: }
93:
94: 95: 96: 97: 98: 99:
100: public function getLength($input)
101: {
102: if (is_scalar($input)) {
103: if ($this->countByChars) {
104: return mb_strlen($input, $this->charset);
105: } else {
106: return strlen($input);
107: }
108: } elseif (is_array($input) || $input instanceof \Countable) {
109: return count($input);
110: } else {
111: return false;
112: }
113: }
114: }
115: