1: <?php
2:
3: namespace Charcoal\Validator;
4:
5: use \InvalidArgumentException;
6:
7:
8: use \Charcoal\Validator\ValidatorInterface;
9: use \Charcoal\Validator\ValidatableInterface;
10: use \Charcoal\Validator\ValidatorResult;
11:
12: 13: 14: 15: 16:
17: abstract class AbstractValidator implements ValidatorInterface
18: {
19: const ERROR = 'error';
20: const WARNING = 'warning';
21: const NOTICE = 'notice';
22:
23: 24: 25:
26: protected $model;
27:
28: 29: 30:
31: private $results = [];
32:
33: 34: 35:
36: public function __construct(ValidatableInterface $model)
37: {
38: $this->model = $model;
39: }
40:
41: 42: 43: 44: 45:
46: public function error($msg, $ident = null)
47: {
48: return $this->log(self::ERROR, $msg, $ident);
49: }
50:
51: 52: 53: 54: 55:
56: public function warning($msg, $ident = null)
57: {
58: return $this->log(self::WARNING, $msg, $ident);
59: }
60:
61: 62: 63: 64: 65:
66: public function notice($msg, $ident = null)
67: {
68: return $this->log(self::NOTICE, $msg, $ident);
69: }
70:
71: 72: 73: 74: 75: 76:
77: public function log($level, $msg, $ident = null)
78: {
79: $this->addResult(
80: [
81: 'ident' => (($ident !== null) ? $ident : ''),
82: 'level' => $level,
83: 'message' => $msg
84: ]
85: );
86: return $this;
87: }
88:
89: 90: 91: 92: 93:
94: public function addResult($result)
95: {
96: if (is_array($result)) {
97: $result = new ValidatorResult($result);
98: } elseif (!($result instanceof ValidatorResult)) {
99: throw new InvalidArgumentException(
100: 'Result must be an array or a ValidatorResult object.'
101: );
102: }
103: $level = $result->level();
104: if (!isset($this->results[$level])) {
105: $this->results[$level] = [];
106: }
107: $this->results[$level][] = $result;
108: return $this;
109: }
110:
111: 112: 113:
114: public function results()
115: {
116: return $this->results;
117: }
118:
119: 120: 121:
122: public function errorResults()
123: {
124: if (!isset($this->results[self::ERROR])) {
125: return [];
126: }
127: return $this->results[self::ERROR];
128: }
129:
130: 131: 132:
133: public function warningResults()
134: {
135: if (!isset($this->results[self::WARNING])) {
136: return [];
137: }
138: return $this->results[self::WARNING];
139: }
140:
141: 142: 143:
144: public function noticeResults()
145: {
146: if (!isset($this->results[self::NOTICE])) {
147: return [];
148: }
149: return $this->results[self::NOTICE];
150: }
151:
152: 153: 154: 155: 156:
157: public function merge(ValidatorInterface $v, $ident_prefix = null)
158: {
159: $results = $v->results();
160: foreach ($results as $level => $levelResults) {
161: foreach ($levelResults as $r) {
162: if ($ident_prefix !== null) {
163: $r->set_ident($ident_prefix.'.'.$r->ident());
164: }
165: $this->addResult($r);
166: }
167: }
168: return $this;
169: }
170:
171: 172: 173:
174: abstract public function validate();
175: }
176: