Complex classes like Schema often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Schema, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
13 | class Schema implements \JsonSerializable { |
||
14 | /** |
||
15 | * Trigger a notice when extraneous properties are encountered during validation. |
||
16 | */ |
||
17 | const VALIDATE_EXTRA_PROPERTY_NOTICE = 0x1; |
||
18 | |||
19 | /** |
||
20 | * Throw a ValidationException when extraneous properties are encountered during validation. |
||
21 | */ |
||
22 | const VALIDATE_EXTRA_PROPERTY_EXCEPTION = 0x2; |
||
23 | |||
24 | /** |
||
25 | * @var array All the known types. |
||
26 | * |
||
27 | * If this is ever given some sort of public access then remove the static. |
||
28 | */ |
||
29 | private static $types = [ |
||
30 | 'array' => ['a'], |
||
31 | 'object' => ['o'], |
||
32 | 'integer' => ['i', 'int'], |
||
33 | 'string' => ['s', 'str'], |
||
34 | 'number' => ['f', 'float'], |
||
35 | 'boolean' => ['b', 'bool'], |
||
36 | 'timestamp' => ['ts'], |
||
37 | 'datetime' => ['dt'], |
||
38 | 'null' => ['n'] |
||
39 | ]; |
||
40 | |||
41 | private $schema = []; |
||
42 | |||
43 | /** |
||
44 | * @var int A bitwise combination of the various **Schema::FLAG_*** constants. |
||
45 | */ |
||
46 | private $flags = 0; |
||
47 | |||
48 | /** |
||
49 | * @var array An array of callbacks that will custom validate the schema. |
||
50 | */ |
||
51 | private $validators = []; |
||
52 | |||
53 | /** |
||
54 | * @var string|Validation The name of the class or an instance that will be cloned. |
||
55 | */ |
||
56 | private $validationClass = Validation::class; |
||
57 | |||
58 | |||
59 | /// Methods /// |
||
60 | |||
61 | /** |
||
62 | * Initialize an instance of a new {@link Schema} class. |
||
63 | * |
||
64 | * @param array $schema The array schema to validate against. |
||
65 | */ |
||
66 | 149 | public function __construct($schema = []) { |
|
69 | |||
70 | /** |
||
71 | * Grab the schema's current description. |
||
72 | * |
||
73 | * @return string |
||
74 | */ |
||
75 | 1 | public function getDescription() { |
|
78 | |||
79 | /** |
||
80 | * Set the description for the schema. |
||
81 | * |
||
82 | * @param string $description The new description. |
||
83 | * @throws \InvalidArgumentException Throws an exception when the provided description is not a string. |
||
84 | * @return Schema |
||
85 | */ |
||
86 | 2 | public function setDescription($description) { |
|
87 | 2 | if (is_string($description)) { |
|
88 | 1 | $this->schema['description'] = $description; |
|
89 | 1 | } else { |
|
90 | 1 | throw new \InvalidArgumentException("The description is not a valid string.", 500); |
|
91 | } |
||
92 | |||
93 | 1 | return $this; |
|
94 | } |
||
95 | |||
96 | /** |
||
97 | * Return the validation flags. |
||
98 | * |
||
99 | * @return int Returns a bitwise combination of flags. |
||
100 | */ |
||
101 | 1 | public function getFlags() { |
|
104 | |||
105 | /** |
||
106 | * Set the validation flags. |
||
107 | * |
||
108 | * @param int $flags One or more of the **Schema::FLAG_*** constants. |
||
109 | * @return Schema Returns the current instance for fluent calls. |
||
110 | */ |
||
111 | 8 | public function setFlags($flags) { |
|
119 | |||
120 | /** |
||
121 | * Whether or not the schema has a flag (or combination of flags). |
||
122 | * |
||
123 | * @param int $flag One or more of the **Schema::VALIDATE_*** constants. |
||
124 | * @return bool Returns **true** if all of the flags are set or **false** otherwise. |
||
125 | */ |
||
126 | 8 | public function hasFlag($flag) { |
|
129 | |||
130 | /** |
||
131 | * Set a flag. |
||
132 | * |
||
133 | * @param int $flag One or more of the **Schema::VALIDATE_*** constants. |
||
134 | * @param bool $value Either true or false. |
||
135 | * @return $this |
||
136 | */ |
||
137 | 1 | public function setFlag($flag, $value) { |
|
145 | |||
146 | /** |
||
147 | * Merge a schema with this one. |
||
148 | * |
||
149 | * @param Schema $schema A scheme instance. Its parameters will be merged into the current instance. |
||
150 | * @return $this |
||
151 | */ |
||
152 | 3 | public function merge(Schema $schema) { |
|
156 | |||
157 | /** |
||
158 | * Add another schema to this one. |
||
159 | * |
||
160 | * Adding schemas together is analogous to array addition. When you add a schema it will only add missing information. |
||
161 | * |
||
162 | * @param Schema $schema The schema to add. |
||
163 | * @param bool $addProperties Whether to add properties that don't exist in this schema. |
||
164 | * @return $this |
||
165 | */ |
||
166 | 3 | public function add(Schema $schema, $addProperties = false) { |
|
170 | |||
171 | /** |
||
172 | * The internal implementation of schema merging. |
||
173 | * |
||
174 | * @param array &$target The target of the merge. |
||
175 | * @param array $source The source of the merge. |
||
176 | * @param bool $overwrite Whether or not to replace values. |
||
177 | * @param bool $addProperties Whether or not to add object properties to the target. |
||
178 | * @return array |
||
179 | */ |
||
180 | 6 | private function mergeInternal(array &$target, array $source, $overwrite = true, $addProperties = true) { |
|
232 | |||
233 | // public function overlay(Schema $schema ) |
||
234 | |||
235 | /** |
||
236 | * Returns the internal schema array. |
||
237 | * |
||
238 | * @return array |
||
239 | * @see Schema::jsonSerialize() |
||
240 | */ |
||
241 | 15 | public function getSchemaArray() { |
|
244 | |||
245 | /** |
||
246 | * Parse a short schema and return the associated schema. |
||
247 | * |
||
248 | * @param array $arr The schema array. |
||
249 | * @param mixed ...$args Constructor arguments for the schema instance. |
||
250 | * @return static Returns a new schema. |
||
251 | */ |
||
252 | 144 | public static function parse(array $arr, ...$args) { |
|
253 | 144 | $schema = new static([], ...$args); |
|
254 | 144 | $schema->schema = $schema->parseInternal($arr); |
|
255 | 144 | return $schema; |
|
256 | } |
||
257 | |||
258 | /** |
||
259 | * Parse a schema in short form into a full schema array. |
||
260 | * |
||
261 | * @param array $arr The array to parse into a schema. |
||
262 | * @return array The full schema array. |
||
263 | * @throws \InvalidArgumentException Throws an exception when an item in the schema is invalid. |
||
264 | */ |
||
265 | 144 | protected function parseInternal(array $arr) { |
|
266 | 144 | if (empty($arr)) { |
|
267 | // An empty schema validates to anything. |
||
268 | 7 | return []; |
|
269 | 138 | } elseif (isset($arr['type'])) { |
|
270 | // This is a long form schema and can be parsed as the root. |
||
271 | return $this->parseNode($arr); |
||
272 | } else { |
||
273 | // Check for a root schema. |
||
274 | 138 | $value = reset($arr); |
|
275 | 138 | $key = key($arr); |
|
276 | 138 | if (is_int($key)) { |
|
277 | 84 | $key = $value; |
|
278 | 84 | $value = null; |
|
279 | 84 | } |
|
280 | 138 | list ($name, $param) = $this->parseShortParam($key, $value); |
|
281 | 138 | if (empty($name)) { |
|
282 | 52 | return $this->parseNode($param, $value); |
|
283 | } |
||
284 | } |
||
285 | |||
286 | // If we are here then this is n object schema. |
||
287 | 88 | list($properties, $required) = $this->parseProperties($arr); |
|
288 | |||
289 | $result = [ |
||
290 | 88 | 'type' => 'object', |
|
291 | 88 | 'properties' => $properties, |
|
292 | 'required' => $required |
||
293 | 88 | ]; |
|
294 | |||
295 | 88 | return array_filter($result); |
|
296 | } |
||
297 | |||
298 | /** |
||
299 | * Parse a schema node. |
||
300 | * |
||
301 | * @param array $node The node to parse. |
||
302 | * @param mixed $value Additional information from the node. |
||
303 | * @return array Returns a JSON schema compatible node. |
||
304 | */ |
||
305 | 138 | private function parseNode($node, $value = null) { |
|
306 | 138 | if (is_array($value)) { |
|
307 | // The value describes a bit more about the schema. |
||
308 | 53 | switch ($node['type']) { |
|
309 | 53 | case 'array': |
|
310 | 7 | if (isset($value['items'])) { |
|
311 | // The value includes array schema information. |
||
312 | 1 | $node = array_replace($node, $value); |
|
313 | 1 | } else { |
|
314 | 6 | $node['items'] = $this->parseInternal($value); |
|
315 | } |
||
316 | 7 | break; |
|
317 | 46 | case 'object': |
|
318 | // The value is a schema of the object. |
||
319 | 10 | if (isset($value['properties'])) { |
|
320 | list($node['properties']) = $this->parseProperties($value['properties']); |
||
321 | } else { |
||
322 | 10 | list($node['properties'], $required) = $this->parseProperties($value); |
|
323 | 10 | if (!empty($required)) { |
|
324 | 10 | $node['required'] = $required; |
|
325 | 10 | } |
|
326 | } |
||
327 | 10 | break; |
|
328 | 36 | default: |
|
329 | 36 | $node = array_replace($node, $value); |
|
330 | 36 | break; |
|
331 | 53 | } |
|
332 | 138 | } elseif (is_string($value)) { |
|
333 | 80 | if ($node['type'] === 'array' && $arrType = $this->getType($value)) { |
|
334 | 2 | $node['items'] = ['type' => $arrType]; |
|
335 | 80 | } elseif (!empty($value)) { |
|
336 | 23 | $node['description'] = $value; |
|
337 | 23 | } |
|
338 | 103 | } elseif ($value === null) { |
|
339 | // Parse child elements. |
||
340 | 24 | if ($node['type'] === 'array' && isset($node['items'])) { |
|
341 | // The value includes array schema information. |
||
342 | $node['items'] = $this->parseInternal($node['items']); |
||
343 | 24 | } elseif ($node['type'] === 'object' && isset($node['properties'])) { |
|
344 | list($node['properties']) = $this->parseProperties($node['properties']); |
||
345 | |||
346 | } |
||
347 | 24 | } |
|
348 | |||
349 | 138 | if (is_array($node) && $node['type'] === null) { |
|
350 | 3 | unset($node['type']); |
|
351 | 3 | } |
|
352 | |||
353 | 138 | return $node; |
|
354 | } |
||
355 | |||
356 | /** |
||
357 | * Parse the schema for an object's properties. |
||
358 | * |
||
359 | * @param array $arr An object property schema. |
||
360 | * @return array Returns a schema array suitable to be placed in the **properties** key of a schema. |
||
361 | */ |
||
362 | 88 | private function parseProperties(array $arr) { |
|
363 | 88 | $properties = []; |
|
364 | 88 | $requiredProperties = []; |
|
365 | 88 | foreach ($arr as $key => $value) { |
|
366 | // Fix a schema specified as just a value. |
||
367 | 88 | if (is_int($key)) { |
|
368 | 64 | if (is_string($value)) { |
|
369 | 64 | $key = $value; |
|
370 | 64 | $value = ''; |
|
371 | 64 | } else { |
|
372 | throw new \InvalidArgumentException("Schema at position $key is not a valid parameter.", 500); |
||
373 | } |
||
374 | 64 | } |
|
375 | |||
376 | // The parameter is defined in the key. |
||
377 | 88 | list($name, $param, $required) = $this->parseShortParam($key, $value); |
|
378 | |||
379 | 88 | $node = $this->parseNode($param, $value); |
|
380 | |||
381 | 88 | $properties[$name] = $node; |
|
382 | 88 | if ($required) { |
|
383 | 46 | $requiredProperties[] = $name; |
|
384 | 46 | } |
|
385 | 88 | } |
|
386 | 88 | return array($properties, $requiredProperties); |
|
387 | } |
||
388 | |||
389 | /** |
||
390 | * Parse a short parameter string into a full array parameter. |
||
391 | * |
||
392 | * @param string $key The short parameter string to parse. |
||
393 | * @param array $value An array of other information that might help resolve ambiguity. |
||
394 | * @return array Returns an array in the form `[string name, array param, bool required]`. |
||
395 | * @throws \InvalidArgumentException Throws an exception if the short param is not in the correct format. |
||
396 | */ |
||
397 | 138 | public function parseShortParam($key, $value = []) { |
|
398 | // Is the parameter optional? |
||
399 | 138 | if (substr($key, -1) === '?') { |
|
400 | 62 | $required = false; |
|
401 | 62 | $key = substr($key, 0, -1); |
|
402 | 62 | } else { |
|
403 | 96 | $required = true; |
|
404 | } |
||
405 | |||
406 | // Check for a type. |
||
407 | 138 | $parts = explode(':', $key); |
|
408 | 138 | $name = $parts[0]; |
|
409 | 138 | $allowNull = false; |
|
410 | 138 | if (!empty($parts[1])) { |
|
411 | 137 | $types = explode('|', $parts[1]); |
|
412 | 137 | foreach ($types as $alias) { |
|
413 | 137 | $found = $this->getType($alias); |
|
414 | 137 | if ($found === null) { |
|
415 | throw new \InvalidArgumentException("Unknown type '$alias'", 500); |
||
416 | 137 | } elseif ($found === 'null') { |
|
417 | 9 | $allowNull = true; |
|
418 | 9 | } else { |
|
419 | 137 | $type = $found; |
|
420 | } |
||
421 | 137 | } |
|
422 | 137 | } else { |
|
423 | 4 | $type = null; |
|
424 | } |
||
425 | |||
426 | 138 | if ($value instanceof Schema) { |
|
427 | 2 | if ($type === 'array') { |
|
428 | 1 | $param = ['type' => $type, 'items' => $value]; |
|
429 | 1 | } else { |
|
430 | 1 | $param = $value; |
|
431 | } |
||
432 | 138 | } elseif (isset($value['type'])) { |
|
433 | $param = $value; |
||
434 | |||
435 | if (!empty($type) && $type !== $param['type']) { |
||
436 | throw new \InvalidArgumentException("Type mismatch between $type and {$param['type']} for field $name.", 500); |
||
437 | } |
||
438 | } else { |
||
439 | 138 | if (empty($type) && !empty($parts[1])) { |
|
440 | throw new \InvalidArgumentException("Invalid type {$parts[1]} for field $name.", 500); |
||
441 | } |
||
442 | 138 | $param = ['type' => $type]; |
|
443 | |||
444 | // Parsed required strings have a minimum length of 1. |
||
445 | 138 | if ($type === 'string' && !empty($name) && $required && (!isset($value['default']) || $value['default'] !== '')) { |
|
446 | 29 | $param['minLength'] = 1; |
|
447 | 29 | } |
|
448 | } |
||
449 | 138 | if ($allowNull) { |
|
450 | 9 | $param['allowNull'] = true; |
|
451 | 9 | } |
|
452 | |||
453 | 138 | return [$name, $param, $required]; |
|
454 | } |
||
455 | |||
456 | /** |
||
457 | * Add a custom validator to to validate the schema. |
||
458 | * |
||
459 | * @param string $fieldname The name of the field to validate, if any. |
||
460 | * |
||
461 | * If you are adding a validator to a deeply nested field then separate the path with dots. |
||
462 | * @param callable $callback The callback to validate with. |
||
463 | * @return Schema Returns `$this` for fluent calls. |
||
464 | */ |
||
465 | 2 | public function addValidator($fieldname, callable $callback) { |
|
466 | 2 | $this->validators[$fieldname][] = $callback; |
|
467 | 2 | return $this; |
|
468 | } |
||
469 | |||
470 | /** |
||
471 | * Require one of a given set of fields in the schema. |
||
472 | * |
||
473 | * @param array $required The field names to require. |
||
474 | * @param string $fieldname The name of the field to attach to. |
||
475 | * @param int $count The count of required items. |
||
476 | * @return Schema Returns `$this` for fluent calls. |
||
477 | */ |
||
478 | 1 | public function requireOneOf(array $required, $fieldname = '', $count = 1) { |
|
479 | 1 | $result = $this->addValidator( |
|
480 | 1 | $fieldname, |
|
481 | function ($data, ValidationField $field) use ($required, $count) { |
||
482 | 1 | $hasCount = 0; |
|
483 | 1 | $flattened = []; |
|
484 | |||
485 | 1 | foreach ($required as $name) { |
|
486 | 1 | $flattened = array_merge($flattened, (array)$name); |
|
487 | |||
488 | 1 | if (is_array($name)) { |
|
489 | // This is an array of required names. They all must match. |
||
490 | 1 | $hasCountInner = 0; |
|
491 | 1 | foreach ($name as $nameInner) { |
|
492 | 1 | if (isset($data[$nameInner]) && $data[$nameInner]) { |
|
493 | 1 | $hasCountInner++; |
|
494 | 1 | } else { |
|
495 | 1 | break; |
|
496 | } |
||
497 | 1 | } |
|
498 | 1 | if ($hasCountInner >= count($name)) { |
|
499 | 1 | $hasCount++; |
|
500 | 1 | } |
|
501 | 1 | } elseif (isset($data[$name]) && $data[$name]) { |
|
502 | 1 | $hasCount++; |
|
503 | 1 | } |
|
504 | |||
505 | 1 | if ($hasCount >= $count) { |
|
506 | 1 | return true; |
|
507 | } |
||
508 | 1 | } |
|
509 | |||
510 | 1 | if ($count === 1) { |
|
511 | 1 | $message = 'One of {required} are required.'; |
|
512 | 1 | } else { |
|
513 | $message = '{count} of {required} are required.'; |
||
514 | } |
||
515 | |||
516 | 1 | $field->addError('missingField', [ |
|
517 | 1 | 'messageCode' => $message, |
|
518 | 1 | 'required' => $required, |
|
519 | 'count' => $count |
||
520 | 1 | ]); |
|
521 | 1 | return false; |
|
522 | } |
||
523 | 1 | ); |
|
524 | |||
525 | 1 | return $result; |
|
526 | } |
||
527 | |||
528 | /** |
||
529 | * Validate data against the schema. |
||
530 | * |
||
531 | * @param mixed $data The data to validate. |
||
532 | * @param bool $sparse Whether or not this is a sparse validation. |
||
533 | * @return mixed Returns a cleaned version of the data. |
||
534 | * @throws ValidationException Throws an exception when the data does not validate against the schema. |
||
535 | */ |
||
536 | 117 | public function validate($data, $sparse = false) { |
|
537 | 117 | $field = new ValidationField($this->createValidation(), $this->schema, ''); |
|
538 | |||
539 | 117 | $clean = $this->validateField($data, $field, $sparse); |
|
540 | |||
541 | 115 | if (Invalid::isInvalid($clean) && $field->isValid()) { |
|
542 | // This really shouldn't happen, but we want to protect against seeing the invalid object. |
||
543 | $field->addError('invalid', ['messageCode' => '{field} is invalid.', 'status' => 422]); |
||
544 | } |
||
545 | |||
546 | 115 | if (!$field->getValidation()->isValid()) { |
|
547 | 63 | throw new ValidationException($field->getValidation()); |
|
548 | } |
||
549 | |||
550 | 71 | return $clean; |
|
551 | } |
||
552 | |||
553 | /** |
||
554 | * Validate data against the schema and return the result. |
||
555 | * |
||
556 | * @param mixed $data The data to validate. |
||
557 | * @param bool $sparse Whether or not to do a sparse validation. |
||
558 | * @return bool Returns true if the data is valid. False otherwise. |
||
559 | */ |
||
560 | 33 | public function isValid($data, $sparse = false) { |
|
561 | try { |
||
562 | 33 | $this->validate($data, $sparse); |
|
563 | 23 | return true; |
|
564 | 24 | } catch (ValidationException $ex) { |
|
565 | 24 | return false; |
|
566 | } |
||
567 | } |
||
568 | |||
569 | /** |
||
570 | * Validate a field. |
||
571 | * |
||
572 | * @param mixed $value The value to validate. |
||
573 | * @param ValidationField $field A validation object to add errors to. |
||
574 | * @param bool $sparse Whether or not this is a sparse validation. |
||
575 | * @return mixed|Invalid Returns a clean version of the value with all extra fields stripped out or invalid if the value |
||
576 | * is completely invalid. |
||
577 | */ |
||
578 | 117 | protected function validateField($value, ValidationField $field, $sparse = false) { |
|
579 | 117 | $result = $value; |
|
580 | 117 | if ($field->getField() instanceof Schema) { |
|
581 | try { |
||
582 | 1 | $result = $field->getField()->validate($value, $sparse); |
|
583 | 1 | } catch (ValidationException $ex) { |
|
584 | // The validation failed, so merge the validations together. |
||
585 | 1 | $field->getValidation()->merge($ex->getValidation(), $field->getName()); |
|
586 | } |
||
587 | 117 | } elseif ($value === null && $field->val('allowNull', false)) { |
|
588 | 9 | $result = $value; |
|
589 | 9 | } else { |
|
590 | // Validate the field's type. |
||
591 | 117 | $type = $field->getType(); |
|
592 | switch ($type) { |
||
593 | 117 | case 'boolean': |
|
594 | 21 | $result = $this->validateBoolean($value, $field); |
|
595 | 21 | break; |
|
596 | 104 | case 'integer': |
|
597 | 23 | $result = $this->validateInteger($value, $field); |
|
598 | 23 | break; |
|
599 | 102 | case 'number': |
|
600 | 9 | $result = $this->validateNumber($value, $field); |
|
601 | 9 | break; |
|
602 | 101 | case 'string': |
|
603 | 52 | $result = $this->validateString($value, $field); |
|
604 | 52 | break; |
|
605 | 84 | case 'timestamp': |
|
606 | 8 | $result = $this->validateTimestamp($value, $field); |
|
607 | 8 | break; |
|
608 | 83 | case 'datetime': |
|
609 | 9 | $result = $this->validateDatetime($value, $field); |
|
610 | 9 | break; |
|
611 | 80 | case 'array': |
|
612 | 13 | $result = $this->validateArray($value, $field, $sparse); |
|
613 | 13 | break; |
|
614 | 78 | case 'object': |
|
615 | 77 | $result = $this->validateObject($value, $field, $sparse); |
|
616 | 75 | break; |
|
617 | 2 | case null: |
|
618 | // No type was specified so we are valid. |
||
619 | 2 | $result = $value; |
|
620 | 2 | break; |
|
621 | default: |
||
622 | throw new \InvalidArgumentException("Unrecognized type $type.", 500); |
||
623 | } |
||
624 | 117 | if (Invalid::isValid($result)) { |
|
625 | 115 | $result = $this->validateEnum($result, $field); |
|
626 | 115 | } |
|
627 | } |
||
628 | |||
629 | // Validate a custom field validator. |
||
630 | 117 | if (Invalid::isValid($result)) { |
|
631 | 115 | $this->callValidators($result, $field); |
|
632 | 115 | } |
|
633 | |||
634 | 117 | return $result; |
|
635 | } |
||
636 | |||
637 | /** |
||
638 | * Validate an array. |
||
639 | * |
||
640 | * @param mixed $value The value to validate. |
||
641 | * @param ValidationField $field The validation results to add. |
||
642 | * @param bool $sparse Whether or not this is a sparse validation. |
||
643 | * @return array|Invalid Returns an array or invalid if validation fails. |
||
644 | */ |
||
645 | 13 | protected function validateArray($value, ValidationField $field, $sparse = false) { |
|
646 | 13 | if ((!is_array($value) || (count($value) > 0 && !array_key_exists(0, $value))) && !$value instanceof \Traversable) { |
|
647 | 7 | $field->addTypeError('array'); |
|
648 | 7 | return Invalid::value(); |
|
649 | 7 | } elseif ($field->val('items') !== null) { |
|
650 | 5 | $result = []; |
|
651 | |||
652 | // Validate each of the types. |
||
653 | 5 | $itemValidation = new ValidationField( |
|
654 | 5 | $field->getValidation(), |
|
655 | 5 | $field->val('items'), |
|
656 | '' |
||
657 | 5 | ); |
|
658 | |||
659 | 5 | $count = 0; |
|
660 | 5 | foreach ($value as $i => $item) { |
|
661 | 5 | $itemValidation->setName($field->getName()."[{$i}]"); |
|
662 | 5 | $validItem = $this->validateField($item, $itemValidation, $sparse); |
|
663 | 5 | if (Invalid::isValid($validItem)) { |
|
664 | 5 | $result[] = $validItem; |
|
665 | 5 | } |
|
666 | 5 | $count++; |
|
667 | 5 | } |
|
668 | |||
669 | 5 | return empty($result) && $count > 0 ? Invalid::value() : $result; |
|
670 | } else { |
||
671 | // Cast the items into a proper numeric array. |
||
672 | 2 | $result = is_array($value) ? array_values($value) : iterator_to_array($value); |
|
673 | 2 | return $result; |
|
674 | } |
||
675 | } |
||
676 | |||
677 | /** |
||
678 | * Validate a boolean value. |
||
679 | * |
||
680 | * @param mixed $value The value to validate. |
||
681 | * @param ValidationField $field The validation results to add. |
||
682 | * @return bool|Invalid Returns the cleaned value or invalid if validation fails. |
||
683 | */ |
||
684 | 21 | protected function validateBoolean($value, ValidationField $field) { |
|
685 | 21 | $value = $value === null ? $value : filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); |
|
686 | 21 | if ($value === null) { |
|
687 | 5 | $field->addTypeError('boolean'); |
|
688 | 5 | return Invalid::value(); |
|
689 | } |
||
690 | 17 | return $value; |
|
691 | } |
||
692 | |||
693 | /** |
||
694 | * Validate a date time. |
||
695 | * |
||
696 | * @param mixed $value The value to validate. |
||
697 | * @param ValidationField $field The validation results to add. |
||
698 | * @return \DateTimeInterface|Invalid Returns the cleaned value or **null** if it isn't valid. |
||
699 | */ |
||
700 | 13 | protected function validateDatetime($value, ValidationField $field) { |
|
701 | 13 | if ($value instanceof \DateTimeInterface) { |
|
702 | // do nothing, we're good |
||
703 | 13 | } elseif (is_string($value) && $value !== '') { |
|
704 | try { |
||
705 | 7 | $dt = new \DateTimeImmutable($value); |
|
706 | 5 | if ($dt) { |
|
707 | 5 | $value = $dt; |
|
708 | 5 | } else { |
|
709 | $value = null; |
||
710 | } |
||
711 | 7 | } catch (\Exception $ex) { |
|
712 | 2 | $value = Invalid::value(); |
|
713 | } |
||
714 | 11 | } elseif (is_int($value) && $value > 0) { |
|
715 | 1 | $value = new \DateTimeImmutable('@'.(string)round($value)); |
|
716 | 1 | } else { |
|
717 | 3 | $value = Invalid::value(); |
|
718 | } |
||
719 | |||
720 | 13 | if (Invalid::isInvalid($value)) { |
|
721 | 5 | $field->addTypeError('datetime'); |
|
722 | 5 | } |
|
723 | 13 | return $value; |
|
724 | } |
||
725 | |||
726 | /** |
||
727 | * Validate a float. |
||
728 | * |
||
729 | * @param mixed $value The value to validate. |
||
730 | * @param ValidationField $field The validation results to add. |
||
731 | * @return float|Invalid Returns a number or **null** if validation fails. |
||
732 | */ |
||
733 | 9 | protected function validateNumber($value, ValidationField $field) { |
|
734 | 9 | $result = filter_var($value, FILTER_VALIDATE_FLOAT); |
|
735 | 9 | if ($result === false) { |
|
736 | 5 | $field->addTypeError('number'); |
|
737 | 5 | return Invalid::value(); |
|
738 | } |
||
739 | 4 | return $result; |
|
740 | } |
||
741 | |||
742 | /** |
||
743 | * Validate and integer. |
||
744 | * |
||
745 | * @param mixed $value The value to validate. |
||
746 | * @param ValidationField $field The validation results to add. |
||
747 | * @return int|Invalid Returns the cleaned value or **null** if validation fails. |
||
748 | */ |
||
749 | 23 | protected function validateInteger($value, ValidationField $field) { |
|
750 | 23 | $result = filter_var($value, FILTER_VALIDATE_INT); |
|
751 | |||
752 | 23 | if ($result === false) { |
|
753 | 9 | $field->addTypeError('integer'); |
|
754 | 9 | return Invalid::value(); |
|
755 | } |
||
756 | 17 | return $result; |
|
757 | } |
||
758 | |||
759 | /** |
||
760 | * Validate an object. |
||
761 | * |
||
762 | * @param mixed $value The value to validate. |
||
763 | * @param ValidationField $field The validation results to add. |
||
764 | * @param bool $sparse Whether or not this is a sparse validation. |
||
765 | * @return object|Invalid Returns a clean object or **null** if validation fails. |
||
766 | */ |
||
767 | 77 | protected function validateObject($value, ValidationField $field, $sparse = false) { |
|
768 | 77 | if (!$this->isArray($value) || isset($value[0])) { |
|
769 | 7 | $field->addTypeError('object'); |
|
770 | 7 | return Invalid::value(); |
|
771 | 77 | } elseif (is_array($field->val('properties'))) { |
|
772 | // Validate the data against the internal schema. |
||
773 | 76 | $value = $this->validateProperties($value, $field, $sparse); |
|
774 | 75 | } elseif (!is_array($value)) { |
|
775 | $value = $this->toArray($value); |
||
776 | } |
||
777 | 75 | return $value; |
|
778 | } |
||
779 | |||
780 | /** |
||
781 | * Validate data against the schema and return the result. |
||
782 | * |
||
783 | * @param array|\ArrayAccess $data The data to validate. |
||
784 | * @param ValidationField $field This argument will be filled with the validation result. |
||
785 | * @param bool $sparse Whether or not this is a sparse validation. |
||
786 | * @return array|Invalid Returns a clean array with only the appropriate properties and the data coerced to proper types. |
||
787 | * or invalid if there are no valid properties. |
||
788 | */ |
||
789 | 76 | protected function validateProperties($data, ValidationField $field, $sparse = false) { |
|
790 | 76 | $properties = $field->val('properties', []); |
|
791 | 76 | $required = array_flip($field->val('required', [])); |
|
792 | |||
793 | 76 | if (is_array($data)) { |
|
794 | 75 | $keys = array_keys($data); |
|
795 | 75 | } else { |
|
796 | 1 | $keys = array_keys(iterator_to_array($data)); |
|
797 | } |
||
798 | 76 | $keys = array_combine(array_map('strtolower', $keys), $keys); |
|
799 | |||
800 | 76 | $propertyField = new ValidationField($field->getValidation(), [], null); |
|
801 | |||
802 | // Loop through the schema fields and validate each one. |
||
803 | 76 | $clean = []; |
|
804 | 76 | foreach ($properties as $propertyName => $property) { |
|
805 | $propertyField |
||
806 | 76 | ->setField($property) |
|
807 | 76 | ->setName(ltrim($field->getName().".$propertyName", '.')); |
|
808 | |||
809 | 76 | $lName = strtolower($propertyName); |
|
810 | 76 | $isRequired = isset($required[$propertyName]); |
|
811 | |||
812 | // First check for required fields. |
||
813 | 76 | if (!array_key_exists($lName, $keys)) { |
|
814 | 20 | if ($sparse) { |
|
815 | // Sparse validation can leave required fields out. |
||
816 | 20 | } elseif ($propertyField->hasVal('default')) { |
|
817 | 2 | $clean[$propertyName] = $propertyField->val('default'); |
|
818 | 20 | } elseif ($isRequired) { |
|
819 | 6 | $propertyField->addError('missingField', ['messageCode' => '{field} is required.']); |
|
820 | 6 | } |
|
821 | 20 | } else { |
|
822 | 74 | $clean[$propertyName] = $this->validateField($data[$keys[$lName]], $propertyField, $sparse); |
|
823 | } |
||
824 | |||
825 | 76 | unset($keys[$lName]); |
|
826 | 76 | } |
|
827 | |||
828 | // Look for extraneous properties. |
||
829 | 76 | if (!empty($keys)) { |
|
830 | 7 | if ($this->hasFlag(Schema::VALIDATE_EXTRA_PROPERTY_NOTICE)) { |
|
831 | 2 | $msg = sprintf("%s has unexpected field(s): %s.", $field->getName() ?: 'value', implode(', ', $keys)); |
|
832 | 2 | trigger_error($msg, E_USER_NOTICE); |
|
833 | } |
||
834 | |||
835 | 5 | if ($this->hasFlag(Schema::VALIDATE_EXTRA_PROPERTY_EXCEPTION)) { |
|
836 | 2 | $field->addError('invalid', [ |
|
837 | 2 | 'messageCode' => '{field} has {extra,plural,an unexpected field,unexpected fields}: {extra}.', |
|
838 | 2 | 'extra' => array_values($keys), |
|
839 | 'status' => 422 |
||
840 | 2 | ]); |
|
841 | 2 | } |
|
842 | 5 | } |
|
843 | |||
844 | 74 | return $clean; |
|
845 | } |
||
846 | |||
847 | /** |
||
848 | * Validate a string. |
||
849 | * |
||
850 | * @param mixed $value The value to validate. |
||
851 | * @param ValidationField $field The validation results to add. |
||
852 | * @return string|Invalid Returns the valid string or **null** if validation fails. |
||
853 | */ |
||
854 | 52 | protected function validateString($value, ValidationField $field) { |
|
855 | 52 | if (is_string($value) || is_numeric($value)) { |
|
856 | 49 | $value = $result = (string)$value; |
|
857 | 49 | } else { |
|
858 | 6 | $field->addTypeError('string'); |
|
859 | 6 | return Invalid::value(); |
|
860 | } |
||
861 | |||
862 | 49 | $errorCount = $field->getErrorCount(); |
|
863 | 49 | if (($minLength = $field->val('minLength', 0)) > 0 && mb_strlen($value) < $minLength) { |
|
864 | 4 | if (!empty($field->getName()) && $minLength === 1) { |
|
865 | 2 | $field->addError('missingField', ['messageCode' => '{field} is required.', 'status' => 422]); |
|
866 | 2 | } else { |
|
867 | 2 | $field->addError( |
|
868 | 2 | 'minLength', |
|
869 | [ |
||
870 | 2 | 'messageCode' => '{field} should be at least {minLength} {minLength,plural,character} long.', |
|
871 | 2 | 'minLength' => $minLength, |
|
872 | 'status' => 422 |
||
873 | 2 | ] |
|
874 | 2 | ); |
|
875 | } |
||
876 | 4 | } |
|
877 | 49 | if (($maxLength = $field->val('maxLength', 0)) > 0 && mb_strlen($value) > $maxLength) { |
|
878 | 1 | $field->addError( |
|
879 | 1 | 'maxLength', |
|
880 | [ |
||
881 | 1 | 'messageCode' => '{field} is {overflow} {overflow,plural,characters} too long.', |
|
882 | 1 | 'maxLength' => $maxLength, |
|
883 | 1 | 'overflow' => mb_strlen($value) - $maxLength, |
|
884 | 'status' => 422 |
||
885 | 1 | ] |
|
886 | 1 | ); |
|
887 | 1 | } |
|
888 | 49 | if ($pattern = $field->val('pattern')) { |
|
889 | 4 | $regex = '`'.str_replace('`', preg_quote('`', '`'), $pattern).'`'; |
|
890 | |||
891 | 4 | if (!preg_match($regex, $value)) { |
|
892 | 2 | $field->addError( |
|
893 | 2 | 'invalid', |
|
894 | [ |
||
895 | 2 | 'messageCode' => '{field} is in the incorrect format.', |
|
896 | 'status' => 422 |
||
897 | 2 | ] |
|
898 | 2 | ); |
|
899 | 2 | } |
|
900 | 4 | } |
|
901 | 49 | if ($format = $field->val('format')) { |
|
902 | 15 | $type = $format; |
|
903 | switch ($format) { |
||
904 | 15 | case 'date-time': |
|
905 | 4 | $result = $this->validateDatetime($result, $field); |
|
906 | 4 | if ($result instanceof \DateTimeInterface) { |
|
907 | 4 | $result = $result->format(\DateTime::RFC3339); |
|
908 | 4 | } |
|
909 | 4 | break; |
|
910 | 11 | case 'email': |
|
911 | 1 | $result = filter_var($result, FILTER_VALIDATE_EMAIL); |
|
912 | 1 | break; |
|
913 | 10 | case 'ipv4': |
|
914 | 1 | $type = 'IPv4 address'; |
|
915 | 1 | $result = filter_var($result, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4); |
|
916 | 1 | break; |
|
917 | 9 | case 'ipv6': |
|
918 | 1 | $type = 'IPv6 address'; |
|
919 | 1 | $result = filter_var($result, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6); |
|
920 | 1 | break; |
|
921 | 8 | case 'ip': |
|
922 | 1 | $type = 'IP address'; |
|
923 | 1 | $result = filter_var($result, FILTER_VALIDATE_IP); |
|
924 | 1 | break; |
|
925 | 7 | case 'uri': |
|
926 | 7 | $type = 'URI'; |
|
927 | 7 | $result = filter_var($result, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED | FILTER_FLAG_SCHEME_REQUIRED); |
|
928 | 7 | break; |
|
929 | default: |
||
930 | trigger_error("Unrecognized format '$format'.", E_USER_NOTICE); |
||
931 | } |
||
932 | 15 | if ($result === false) { |
|
933 | 5 | $field->addTypeError($type); |
|
934 | 5 | } |
|
935 | 15 | } |
|
936 | |||
937 | 49 | if ($field->isValid()) { |
|
938 | 41 | return $result; |
|
939 | } else { |
||
940 | 12 | return Invalid::value(); |
|
941 | } |
||
942 | } |
||
943 | |||
944 | /** |
||
945 | * Validate a unix timestamp. |
||
946 | * |
||
947 | * @param mixed $value The value to validate. |
||
948 | * @param ValidationField $field The field being validated. |
||
949 | * @return int|Invalid Returns a valid timestamp or invalid if the value doesn't validate. |
||
950 | */ |
||
951 | 8 | protected function validateTimestamp($value, ValidationField $field) { |
|
952 | 8 | if (is_numeric($value) && $value > 0) { |
|
953 | 2 | $result = (int)$value; |
|
954 | 8 | } elseif (is_string($value) && $ts = strtotime($value)) { |
|
955 | 1 | $result = $ts; |
|
956 | 1 | } else { |
|
957 | 5 | $field->addTypeError('timestamp'); |
|
958 | 5 | $result = Invalid::value(); |
|
959 | } |
||
960 | 8 | return $result; |
|
961 | } |
||
962 | |||
963 | /** |
||
964 | * Validate a null value. |
||
965 | * |
||
966 | * @param mixed $value The value to validate. |
||
967 | * @param ValidationField $field The error collector for the field. |
||
968 | * @return null|Invalid Returns **null** or invalid. |
||
969 | */ |
||
970 | protected function validateNull($value, ValidationField $field) { |
||
971 | if ($value === null) { |
||
972 | return null; |
||
973 | } |
||
974 | $field->addError('invalid', ['messageCode' => '{field} should be null.', 'status' => 422]); |
||
975 | return Invalid::value(); |
||
976 | } |
||
977 | |||
978 | /** |
||
979 | * Validate a value against an enum. |
||
980 | * |
||
981 | * @param mixed $value The value to test. |
||
982 | * @param ValidationField $field The validation object for adding errors. |
||
983 | * @return mixed|Invalid Returns the value if it is one of the enumerated values or invalid otherwise. |
||
984 | */ |
||
985 | 115 | protected function validateEnum($value, ValidationField $field) { |
|
986 | 115 | $enum = $field->val('enum'); |
|
987 | 115 | if (empty($enum)) { |
|
988 | 114 | return $value; |
|
989 | } |
||
990 | |||
991 | 1 | if (!in_array($value, $enum, true)) { |
|
992 | 1 | $field->addError( |
|
993 | 1 | 'invalid', |
|
994 | [ |
||
995 | 1 | 'messageCode' => '{field} must be one of: {enum}.', |
|
996 | 1 | 'enum' => $enum, |
|
997 | 'status' => 422 |
||
998 | 1 | ] |
|
999 | 1 | ); |
|
1000 | 1 | return Invalid::value(); |
|
1001 | } |
||
1002 | 1 | return $value; |
|
1003 | } |
||
1004 | |||
1005 | /** |
||
1006 | * Call all of the validators attached to a field. |
||
1007 | * |
||
1008 | * @param mixed $value The field value being validated. |
||
1009 | * @param ValidationField $field The validation object to add errors. |
||
1010 | */ |
||
1011 | 115 | protected function callValidators($value, ValidationField $field) { |
|
1012 | 115 | $valid = true; |
|
1013 | |||
1014 | // Strip array references in the name except for the last one. |
||
1015 | 115 | $key = preg_replace(['`\[\d+\]$`', '`\[\d+\]`'], ['[]', ''], $field->getName()); |
|
1016 | 115 | if (!empty($this->validators[$key])) { |
|
1017 | 2 | foreach ($this->validators[$key] as $validator) { |
|
1018 | 2 | $r = call_user_func($validator, $value, $field); |
|
1019 | |||
1020 | 2 | if ($r === false || Invalid::isInvalid($r)) { |
|
1021 | 1 | $valid = false; |
|
1022 | 1 | } |
|
1023 | 2 | } |
|
1024 | 2 | } |
|
1025 | |||
1026 | // Add an error on the field if the validator hasn't done so. |
||
1027 | 115 | if (!$valid && $field->isValid()) { |
|
1028 | $field->addError('invalid', ['messageCode' => '{field} is invalid.', 'status' => 422]); |
||
1029 | } |
||
1030 | 115 | } |
|
1031 | |||
1032 | /** |
||
1033 | * Specify data which should be serialized to JSON. |
||
1034 | * |
||
1035 | * This method specifically returns data compatible with the JSON schema format. |
||
1036 | * |
||
1037 | * @return mixed Returns data which can be serialized by **json_encode()**, which is a value of any type other than a resource. |
||
1038 | * @link http://php.net/manual/en/jsonserializable.jsonserialize.php |
||
1039 | * @link http://json-schema.org/ |
||
1040 | */ |
||
1041 | public function jsonSerialize() { |
||
1076 | |||
1077 | /** |
||
1078 | * Look up a type based on its alias. |
||
1079 | * |
||
1080 | * @param string $alias The type alias or type name to lookup. |
||
1081 | * @return mixed |
||
1082 | */ |
||
1083 | 137 | protected function getType($alias) { |
|
1084 | 137 | if (isset(self::$types[$alias])) { |
|
1085 | return $alias; |
||
1086 | } |
||
1087 | 137 | foreach (self::$types as $type => $aliases) { |
|
1088 | 137 | if (in_array($alias, $aliases, true)) { |
|
1089 | 137 | return $type; |
|
1090 | } |
||
1091 | 137 | } |
|
1092 | 8 | return null; |
|
1093 | } |
||
1094 | |||
1095 | /** |
||
1096 | * Get the class that's used to contain validation information. |
||
1097 | * |
||
1098 | * @return Validation|string Returns the validation class. |
||
1099 | */ |
||
1100 | 117 | public function getValidationClass() { |
|
1103 | |||
1104 | /** |
||
1105 | * Set the class that's used to contain validation information. |
||
1106 | * |
||
1107 | * @param Validation|string $class Either the name of a class or a class that will be cloned. |
||
1108 | * @return $this |
||
1109 | */ |
||
1110 | 1 | public function setValidationClass($class) { |
|
1118 | |||
1119 | /** |
||
1120 | * Create a new validation instance. |
||
1121 | * |
||
1122 | * @return Validation Returns a validation object. |
||
1123 | */ |
||
1124 | 117 | protected function createValidation() { |
|
1134 | |||
1135 | /** |
||
1136 | * Check whether or not a value is an array or accessible like an array. |
||
1137 | * |
||
1138 | * @param mixed $value The value to check. |
||
1139 | * @return bool Returns **true** if the value can be used like an array or **false** otherwise. |
||
1140 | */ |
||
1141 | 77 | private function isArray($value) { |
|
1144 | |||
1145 | /** |
||
1146 | * Cast a value to an array. |
||
1147 | * |
||
1148 | * @param \Traversable $value The value to convert. |
||
1149 | * @return array Returns an array. |
||
1150 | */ |
||
1151 | private function toArray(\Traversable $value) { |
||
1157 | } |
||
1158 |
This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.
To visualize
will produce issues in the first and second line, while this second example
will produce no issues.