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 input is existing table record
13: *
14: * @author Twin Huang <twinhuang@qq.com>
15: */
16: class RecordExists extends BaseValidator
17: {
18: /**
19: * The message added when query return empty result
20: *
21: * @var string
22: */
23: protected $notFoundMessage = '%name% not exists';
24:
25: /**
26: * The message for negative mode
27: *
28: * @var string
29: */
30: protected $negativeMessage = '%name% already exists';
31:
32: /**
33: * The name of table
34: *
35: * @var string
36: */
37: protected $table;
38:
39: /**
40: * The field to search
41: *
42: * @var string
43: */
44: protected $field = 'id';
45:
46: /**
47: * The data fetch from database
48: *
49: * @var array
50: */
51: protected $data = array();
52:
53: /**
54: * Check if the input is existing table record
55: *
56: * @param string $input
57: * @param string $table
58: * @param string $field
59: * @return bool
60: */
61: public function __invoke($input = null, $table = null, $field = 'id')
62: {
63: $table && $this->storeOption('table', $table);
64: $field && $this->storeOption('field', $field);
65:
66: return $this->isValid($input);
67: }
68:
69: /**
70: * {@inheritdoc}
71: */
72: protected function doValidate($input)
73: {
74: if (!$this->isString($input)) {
75: $this->addError('notString');
76: return false;
77: }
78:
79: $this->data = $this->db->find($this->table, array($this->field => $input));
80:
81: if (empty($this->data)) {
82: $this->addError('notFound');
83: return false;
84: }
85:
86: return true;
87: }
88:
89: /**
90: * Returns the data fetch from database
91: *
92: * @return array
93: */
94: public function getData()
95: {
96: return $this->data;
97: }
98: }
99: