Debian Codegraph @

vendor/ipl/validator/src/ValidatorChain.php

raw
1 <?php
2
3 namespace ipl\Validator;
4
5 use Countable;
6 use InvalidArgumentException;
7 use ipl\Stdlib\Contract\Validator;
8 use ipl\Stdlib\Messages;
9 use ipl\Stdlib\Plugins;
10 use ipl\Stdlib\PriorityQueue;
11 use IteratorAggregate;
12 use SplObjectStorage;
13 use Traversable;
14 use UnexpectedValueException;
15
16 use function ipl\Stdlib\get_php_type;
17
18 /**
19 * Chain multiple validators and run them in sequence
20 *
21 * @implements IteratorAggregate<int, Validator>
22 */
23 class ValidatorChain implements Countable, IteratorAggregate, Validator
24 {
25 use Messages;
26 use Plugins;
27
28 /** @var int Default priority at which validators are added */
29 public const DEFAULT_PRIORITY = 1;
30
31 /** @var PriorityQueue<int, Validator> Validator chain */
32 protected PriorityQueue $validators;
33
34 /** @var SplObjectStorage<Validator, null> Validators that break the chain on failure */
35 protected SplObjectStorage $validatorsThatBreakTheChain;
36
37 /**
38 * Create a new validator chain
39 */
40 public function __construct()
41 {
42 $this->validators = new PriorityQueue();
43 $this->validatorsThatBreakTheChain = new SplObjectStorage();
44
45 $this->addDefaultPluginLoader('validator', __NAMESPACE__, 'Validator');
46 }
47
48 /**
49 * Get the validators that break the chain
50 *
51 * @return SplObjectStorage<Validator, null>
52 */
53 public function getValidatorsThatBreakTheChain(): SplObjectStorage
54 {
55 return $this->validatorsThatBreakTheChain;
56 }
57
58 /**
59 * Add a validator to the chain
60 *
61 * If $breakChainOnFailure is true and the validator fails, subsequent validators won't be executed.
62 *
63 * @param Validator $validator
64 * @param bool $breakChainOnFailure
65 * @param int $priority Priority at which to add validator
66 *
67 * @return $this
68 */
69 public function add(
70 Validator $validator,
71 bool $breakChainOnFailure = false,
72 int $priority = self::DEFAULT_PRIORITY
73 ): static {
74 $this->validators->insert($validator, $priority);
75
76 if ($breakChainOnFailure) {
77 $this->validatorsThatBreakTheChain->offsetSet($validator);
78 }
79
80 return $this;
81 }
82
83 /**
84 * Add the validators from the given validator specification to the chain
85 *
86 * @param static|Traversable<int|string, mixed> $validators
87 *
88 * @return $this
89 *
90 * @throws InvalidArgumentException If $validators is not iterable or if the validator specification is invalid
91 */
92 public function addValidators($validators): static
93 {
94 if ($validators instanceof static) {
95 return $this->merge($validators);
96 }
97
98 if (! is_iterable($validators)) {
99 throw new InvalidArgumentException(sprintf(
100 '%s expects parameter one to be iterable, got %s instead',
101 __METHOD__,
102 get_php_type($validators)
103 ));
104 }
105
106 foreach ($validators as $name => $validator) {
107 $breakChainOnFailure = false;
108
109 if (! $validator instanceof Validator) {
110 if (is_int($name)) {
111 if (! is_array($validator)) {
112 $name = $validator;
113 $validator = null;
114 } else {
115 if (! isset($validator['name'])) {
116 throw new InvalidArgumentException(
117 'Invalid validator array specification: Key "name" is missing'
118 );
119 }
120
121 $name = $validator['name'];
122 unset($validator['name']);
123 }
124 }
125
126 if (is_array($validator)) {
127 if (isset($validator['options'])) {
128 $options = $validator['options'];
129
130 unset($validator['options']);
131
132 $validator = array_merge($validator, $options);
133 }
134
135 if (isset($validator['break_chain_on_failure'])) {
136 $breakChainOnFailure = $validator['break_chain_on_failure'];
137
138 unset($validator['break_chain_on_failure']);
139 }
140 }
141
142 $validator = $this->createValidator($name, $validator);
143 }
144
145 $this->add($validator, $breakChainOnFailure);
146 }
147
148 return $this;
149 }
150
151 /**
152 * Add a validator loader
153 *
154 * @param string $namespace Namespace of the validators
155 * @param string $postfix Validator name postfix, if any
156 *
157 * @return $this
158 */
159 public function addValidatorLoader(string $namespace, string $postfix = ''): static
160 {
161 $this->addPluginLoader('validator', $namespace, $postfix);
162
163 return $this;
164 }
165
166 /**
167 * Remove all validators from the chain
168 *
169 * @return $this
170 */
171 public function clearValidators(): static
172 {
173 $this->validators = new PriorityQueue();
174 $this->validatorsThatBreakTheChain = new SplObjectStorage();
175
176 return $this;
177 }
178
179 /**
180 * Create a validator from the given name and options
181 *
182 * @param string $name
183 * @param mixed $options
184 *
185 * @return Validator
186 *
187 * @throws InvalidArgumentException If the validator to load is unknown
188 * @throws UnexpectedValueException If a validator loader did not return an instance of {@see Validator}
189 */
190 public function createValidator(string $name, mixed $options = null): Validator
191 {
192 $class = $this->loadPlugin('validator', $name);
193
194 if (! $class) {
195 throw new InvalidArgumentException(sprintf(
196 "Can't load validator '%s'. Validator unknown",
197 $name
198 ));
199 }
200
201 if (empty($options)) {
202 $validator = new $class();
203 } else {
204 $validator = new $class($options);
205 }
206
207 if (! $validator instanceof Validator) {
208 throw new UnexpectedValueException(sprintf(
209 "%s expects loader to return an instance of %s for validator '%s', got %s instead",
210 __METHOD__,
211 Validator::class,
212 $name,
213 get_php_type($validator)
214 ));
215 }
216
217 return $validator;
218 }
219
220 /**
221 * Merge all validators from the given chain into this one
222 *
223 * @param ValidatorChain $validatorChain
224 *
225 * @return $this
226 */
227 public function merge(ValidatorChain $validatorChain): static
228 {
229 $validatorsThatBreakTheChain = $validatorChain->getValidatorsThatBreakTheChain();
230
231 /**
232 * @var int $priority
233 * @var Validator $validator
234 */
235 foreach ($validatorChain->validators->yieldAll() as $priority => $validator) {
236 $this->add($validator, $validatorsThatBreakTheChain->offsetExists($validator), $priority);
237 }
238
239 return $this;
240 }
241
242 /**
243 * Clone the validator chain, ensuring the internal queue is also cloned
244 */
245 public function __clone()
246 {
247 $this->validators = clone $this->validators;
248 }
249
250 /**
251 * Export the chain as array
252 *
253 * @return Validator[]
254 */
255 public function toArray(): array
256 {
257 /** @var Validator[] $validators */
258 $validators = iterator_to_array($this);
259
260 return array_values($validators);
261 }
262
263 /**
264 * Get the number of validators in the chain
265 *
266 * @return int
267 */
268 public function count(): int
269 {
270 return count($this->validators);
271 }
272
273 /**
274 * Get an iterator for traversing the validators
275 *
276 * @return PriorityQueue<int, Validator>
277 */
278 public function getIterator(): Traversable
279 {
280 // Clone because PriorityQueue removes items during iteration.
281 return clone $this->validators;
282 }
283
284 /**
285 * Check whether the value passes all validators in the chain
286 *
287 * @param mixed $value
288 *
289 * @return bool
290 */
291 public function isValid($value): bool
292 {
293 $this->clearMessages();
294
295 $valid = true;
296
297 foreach ($this as $validator) {
298 if ($validator->isValid($value)) {
299 continue;
300 }
301
302 $valid = false;
303
304 $this->addMessages($validator->getMessages());
305
306 if ($this->validatorsThatBreakTheChain->offsetExists($validator)) {
307 break;
308 }
309 }
310
311 return $valid;
312 }
313 }