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 validate fields data is exists
13: *
14: * @author Twin Huang <twinhuang@qq.com>
15: */
16: class FieldExists extends BaseValidator
17: {
18: protected $tooFewMessage = '%name% must contain at least %min% item(s)';
19:
20: protected $tooManyMessage = '%name% must contain no more than %max% items';
21:
22: protected $lengthMessage = '%name% must contain %length% item(s)';
23:
24: /**
25: * Which fields should exists in validate data
26: *
27: * @var array
28: */
29: protected $fields = array();
30:
31: /**
32: * How many fields should exist
33: *
34: * @var int
35: */
36: protected $length;
37:
38: /**
39: * How many fields should exist at least
40: *
41: * @var int
42: */
43: protected $min;
44:
45: /**
46: * How many fields should exist at most
47: *
48: * @var int
49: */
50: protected $max;
51:
52: /**
53: * How many fields found in validate data
54: *
55: * @var int
56: */
57: protected $count;
58:
59: /**
60: * {@inheritdoc}
61: */
62: protected function doValidate($input)
63: {
64: $this->count = 0;
65: foreach ($this->fields as $field) {
66: if ($this->validator->getFieldData($field)) {
67: $this->count++;
68: }
69: }
70:
71: if (!is_null($this->length) && $this->count != $this->length) {
72: $this->addError('length');
73: return false;
74: }
75:
76: if (!is_null($this->min) && $this->count < $this->min) {
77: $this->addError('tooFew');
78: return false;
79: }
80:
81: if (!is_null($this->max) && $this->count > $this->max) {
82: $this->addError('tooMany');
83: return false;
84: }
85:
86: return true;
87: }
88: }
89: