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, \ArrayAccess { |
||
| 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 | /** |
||
| 42 | * @var string The regular expression to strictly determine if a string is a date. |
||
| 43 | */ |
||
| 44 | private static $DATE_REGEX = '`^\d{4}-\d{2}-\d{2}([ T]\d{2}:\d{2}(:\d{2})?)?`i'; |
||
| 45 | |||
| 46 | private $schema = []; |
||
| 47 | |||
| 48 | /** |
||
| 49 | * @var int A bitwise combination of the various **Schema::FLAG_*** constants. |
||
| 50 | */ |
||
| 51 | private $flags = 0; |
||
| 52 | |||
| 53 | /** |
||
| 54 | * @var array An array of callbacks that will filter data in the schema. |
||
| 55 | */ |
||
| 56 | private $filters = []; |
||
| 57 | |||
| 58 | /** |
||
| 59 | * @var array An array of callbacks that will custom validate the schema. |
||
| 60 | */ |
||
| 61 | private $validators = []; |
||
| 62 | |||
| 63 | /** |
||
| 64 | * @var string|Validation The name of the class or an instance that will be cloned. |
||
| 65 | */ |
||
| 66 | private $validationClass = Validation::class; |
||
| 67 | |||
| 68 | |||
| 69 | /// Methods /// |
||
| 70 | |||
| 71 | /** |
||
| 72 | * Initialize an instance of a new {@link Schema} class. |
||
| 73 | * |
||
| 74 | * @param array $schema The array schema to validate against. |
||
| 75 | */ |
||
| 76 | 173 | public function __construct($schema = []) { |
|
| 79 | |||
| 80 | /** |
||
| 81 | * Grab the schema's current description. |
||
| 82 | * |
||
| 83 | * @return string |
||
| 84 | */ |
||
| 85 | 1 | public function getDescription() { |
|
| 88 | |||
| 89 | /** |
||
| 90 | * Set the description for the schema. |
||
| 91 | * |
||
| 92 | * @param string $description The new description. |
||
| 93 | * @throws \InvalidArgumentException Throws an exception when the provided description is not a string. |
||
| 94 | * @return Schema |
||
| 95 | */ |
||
| 96 | 2 | public function setDescription($description) { |
|
| 105 | |||
| 106 | /** |
||
| 107 | * Get a schema field. |
||
| 108 | * |
||
| 109 | * @param string|array $path The JSON schema path of the field with parts separated by dots. |
||
| 110 | * @param mixed $default The value to return if the field isn't found. |
||
| 111 | * @return mixed Returns the field value or `$default`. |
||
| 112 | */ |
||
| 113 | 5 | public function getField($path, $default = null) { |
|
| 130 | |||
| 131 | /** |
||
| 132 | * Set a schema field. |
||
| 133 | * |
||
| 134 | * @param string|array $path The JSON schema path of the field with parts separated by dots. |
||
| 135 | * @param mixed $value The new value. |
||
| 136 | * @return $this |
||
| 137 | */ |
||
| 138 | 3 | public function setField($path, $value) { |
|
| 161 | |||
| 162 | /** |
||
| 163 | * Get the ID for the schema. |
||
| 164 | * |
||
| 165 | * @return string |
||
| 166 | */ |
||
| 167 | 3 | public function getID() { |
|
| 170 | |||
| 171 | /** |
||
| 172 | * Set the ID for the schema. |
||
| 173 | * |
||
| 174 | * @param string $id The new ID. |
||
| 175 | * @throws \InvalidArgumentException Throws an exception when the provided ID is not a string. |
||
| 176 | * @return Schema |
||
| 177 | */ |
||
| 178 | 1 | public function setID($id) { |
|
| 187 | |||
| 188 | /** |
||
| 189 | * Return the validation flags. |
||
| 190 | * |
||
| 191 | * @return int Returns a bitwise combination of flags. |
||
| 192 | */ |
||
| 193 | 1 | public function getFlags() { |
|
| 196 | |||
| 197 | /** |
||
| 198 | * Set the validation flags. |
||
| 199 | * |
||
| 200 | * @param int $flags One or more of the **Schema::FLAG_*** constants. |
||
| 201 | * @return Schema Returns the current instance for fluent calls. |
||
| 202 | */ |
||
| 203 | 8 | public function setFlags($flags) { |
|
| 211 | |||
| 212 | /** |
||
| 213 | * Whether or not the schema has a flag (or combination of flags). |
||
| 214 | * |
||
| 215 | * @param int $flag One or more of the **Schema::VALIDATE_*** constants. |
||
| 216 | * @return bool Returns **true** if all of the flags are set or **false** otherwise. |
||
| 217 | */ |
||
| 218 | 10 | public function hasFlag($flag) { |
|
| 221 | |||
| 222 | /** |
||
| 223 | * Set a flag. |
||
| 224 | * |
||
| 225 | * @param int $flag One or more of the **Schema::VALIDATE_*** constants. |
||
| 226 | * @param bool $value Either true or false. |
||
| 227 | * @return $this |
||
| 228 | */ |
||
| 229 | 1 | public function setFlag($flag, $value) { |
|
| 237 | |||
| 238 | /** |
||
| 239 | * Merge a schema with this one. |
||
| 240 | * |
||
| 241 | * @param Schema $schema A scheme instance. Its parameters will be merged into the current instance. |
||
| 242 | * @return $this |
||
| 243 | */ |
||
| 244 | 3 | public function merge(Schema $schema) { |
|
| 248 | |||
| 249 | /** |
||
| 250 | * Add another schema to this one. |
||
| 251 | * |
||
| 252 | * Adding schemas together is analogous to array addition. When you add a schema it will only add missing information. |
||
| 253 | * |
||
| 254 | * @param Schema $schema The schema to add. |
||
| 255 | * @param bool $addProperties Whether to add properties that don't exist in this schema. |
||
| 256 | * @return $this |
||
| 257 | */ |
||
| 258 | 3 | public function add(Schema $schema, $addProperties = false) { |
|
| 262 | |||
| 263 | /** |
||
| 264 | * The internal implementation of schema merging. |
||
| 265 | * |
||
| 266 | * @param array &$target The target of the merge. |
||
| 267 | * @param array $source The source of the merge. |
||
| 268 | * @param bool $overwrite Whether or not to replace values. |
||
| 269 | * @param bool $addProperties Whether or not to add object properties to the target. |
||
| 270 | * @return array |
||
| 271 | */ |
||
| 272 | 6 | private function mergeInternal(array &$target, array $source, $overwrite = true, $addProperties = true) { |
|
| 324 | |||
| 325 | // public function overlay(Schema $schema ) |
||
| 326 | |||
| 327 | /** |
||
| 328 | * Returns the internal schema array. |
||
| 329 | * |
||
| 330 | * @return array |
||
| 331 | * @see Schema::jsonSerialize() |
||
| 332 | */ |
||
| 333 | 8 | public function getSchemaArray() { |
|
| 336 | |||
| 337 | /** |
||
| 338 | * Parse a short schema and return the associated schema. |
||
| 339 | * |
||
| 340 | * @param array $arr The schema array. |
||
| 341 | * @param mixed ...$args Constructor arguments for the schema instance. |
||
| 342 | * @return static Returns a new schema. |
||
| 343 | */ |
||
| 344 | 142 | public static function parse(array $arr, ...$args) { |
|
| 349 | |||
| 350 | /** |
||
| 351 | * Parse a schema in short form into a full schema array. |
||
| 352 | * |
||
| 353 | * @param array $arr The array to parse into a schema. |
||
| 354 | * @return array The full schema array. |
||
| 355 | * @throws \InvalidArgumentException Throws an exception when an item in the schema is invalid. |
||
| 356 | */ |
||
| 357 | 142 | protected function parseInternal(array $arr) { |
|
| 389 | |||
| 390 | /** |
||
| 391 | * Parse a schema node. |
||
| 392 | * |
||
| 393 | * @param array $node The node to parse. |
||
| 394 | * @param mixed $value Additional information from the node. |
||
| 395 | * @return array Returns a JSON schema compatible node. |
||
| 396 | */ |
||
| 397 | 136 | private function parseNode($node, $value = null) { |
|
| 454 | |||
| 455 | /** |
||
| 456 | * Parse the schema for an object's properties. |
||
| 457 | * |
||
| 458 | * @param array $arr An object property schema. |
||
| 459 | * @return array Returns a schema array suitable to be placed in the **properties** key of a schema. |
||
| 460 | */ |
||
| 461 | 91 | private function parseProperties(array $arr) { |
|
| 487 | |||
| 488 | /** |
||
| 489 | * Parse a short parameter string into a full array parameter. |
||
| 490 | * |
||
| 491 | * @param string $key The short parameter string to parse. |
||
| 492 | * @param array $value An array of other information that might help resolve ambiguity. |
||
| 493 | * @return array Returns an array in the form `[string name, array param, bool required]`. |
||
| 494 | * @throws \InvalidArgumentException Throws an exception if the short param is not in the correct format. |
||
| 495 | */ |
||
| 496 | 136 | public function parseShortParam($key, $value = []) { |
|
| 555 | |||
| 556 | /** |
||
| 557 | * Add a custom filter to change data before validation. |
||
| 558 | * |
||
| 559 | * @param string $fieldname The name of the field to filter, if any. |
||
| 560 | * |
||
| 561 | * If you are adding a filter to a deeply nested field then separate the path with dots. |
||
| 562 | * @param callable $callback The callback to filter the field. |
||
| 563 | * @return $this |
||
| 564 | */ |
||
| 565 | 1 | public function addFilter($fieldname, callable $callback) { |
|
| 569 | |||
| 570 | /** |
||
| 571 | * Add a custom validator to to validate the schema. |
||
| 572 | * |
||
| 573 | * @param string $fieldname The name of the field to validate, if any. |
||
| 574 | * |
||
| 575 | * If you are adding a validator to a deeply nested field then separate the path with dots. |
||
| 576 | * @param callable $callback The callback to validate with. |
||
| 577 | * @return Schema Returns `$this` for fluent calls. |
||
| 578 | */ |
||
| 579 | 4 | public function addValidator($fieldname, callable $callback) { |
|
| 583 | |||
| 584 | /** |
||
| 585 | * Require one of a given set of fields in the schema. |
||
| 586 | * |
||
| 587 | * @param array $required The field names to require. |
||
| 588 | * @param string $fieldname The name of the field to attach to. |
||
| 589 | * @param int $count The count of required items. |
||
| 590 | * @return Schema Returns `$this` for fluent calls. |
||
| 591 | */ |
||
| 592 | 3 | public function requireOneOf(array $required, $fieldname = '', $count = 1) { |
|
| 593 | 3 | $result = $this->addValidator( |
|
| 594 | 3 | $fieldname, |
|
| 595 | 3 | function ($data, ValidationField $field) use ($required, $count) { |
|
| 596 | // This validator does not apply to sparse validation. |
||
| 597 | 3 | if ($field->isSparse()) { |
|
| 598 | 1 | return true; |
|
| 599 | } |
||
| 600 | |||
| 601 | 2 | $hasCount = 0; |
|
| 602 | 2 | $flattened = []; |
|
| 603 | |||
| 604 | 2 | foreach ($required as $name) { |
|
| 605 | 2 | $flattened = array_merge($flattened, (array)$name); |
|
| 606 | |||
| 607 | 2 | if (is_array($name)) { |
|
| 608 | // This is an array of required names. They all must match. |
||
| 609 | 1 | $hasCountInner = 0; |
|
| 610 | 1 | foreach ($name as $nameInner) { |
|
| 611 | 1 | if (array_key_exists($nameInner, $data)) { |
|
| 612 | 1 | $hasCountInner++; |
|
| 613 | } else { |
||
| 614 | 1 | break; |
|
| 615 | } |
||
| 616 | } |
||
| 617 | 1 | if ($hasCountInner >= count($name)) { |
|
| 618 | 1 | $hasCount++; |
|
| 619 | } |
||
| 620 | 2 | } elseif (array_key_exists($name, $data)) { |
|
| 621 | 1 | $hasCount++; |
|
| 622 | } |
||
| 623 | |||
| 624 | 2 | if ($hasCount >= $count) { |
|
| 625 | 2 | return true; |
|
| 626 | } |
||
| 627 | } |
||
| 628 | |||
| 629 | 2 | if ($count === 1) { |
|
| 630 | 1 | $message = 'One of {required} are required.'; |
|
| 631 | } else { |
||
| 632 | 1 | $message = '{count} of {required} are required.'; |
|
| 633 | } |
||
| 634 | |||
| 635 | 2 | $field->addError('missingField', [ |
|
| 636 | 2 | 'messageCode' => $message, |
|
| 637 | 2 | 'required' => $required, |
|
| 638 | 2 | 'count' => $count |
|
| 639 | ]); |
||
| 640 | 2 | return false; |
|
| 641 | 3 | } |
|
| 642 | ); |
||
| 643 | |||
| 644 | 3 | return $result; |
|
| 645 | } |
||
| 646 | |||
| 647 | /** |
||
| 648 | * Validate data against the schema. |
||
| 649 | * |
||
| 650 | * @param mixed $data The data to validate. |
||
| 651 | * @param bool $sparse Whether or not this is a sparse validation. |
||
| 652 | * @return mixed Returns a cleaned version of the data. |
||
| 653 | * @throws ValidationException Throws an exception when the data does not validate against the schema. |
||
| 654 | */ |
||
| 655 | 142 | public function validate($data, $sparse = false) { |
|
| 656 | 142 | $field = new ValidationField($this->createValidation(), $this->schema, '', $sparse); |
|
| 657 | |||
| 658 | 142 | $clean = $this->validateField($data, $field, $sparse); |
|
| 659 | |||
| 660 | 140 | if (Invalid::isInvalid($clean) && $field->isValid()) { |
|
| 661 | // This really shouldn't happen, but we want to protect against seeing the invalid object. |
||
| 662 | $field->addError('invalid', ['messageCode' => '{field} is invalid.', 'status' => 422]); |
||
| 663 | } |
||
| 664 | |||
| 665 | 140 | if (!$field->getValidation()->isValid()) { |
|
| 666 | 52 | throw new ValidationException($field->getValidation()); |
|
| 667 | } |
||
| 668 | |||
| 669 | 102 | return $clean; |
|
| 670 | } |
||
| 671 | |||
| 672 | /** |
||
| 673 | * Validate data against the schema and return the result. |
||
| 674 | * |
||
| 675 | * @param mixed $data The data to validate. |
||
| 676 | * @param bool $sparse Whether or not to do a sparse validation. |
||
| 677 | * @return bool Returns true if the data is valid. False otherwise. |
||
| 678 | */ |
||
| 679 | 21 | public function isValid($data, $sparse = false) { |
|
| 687 | |||
| 688 | /** |
||
| 689 | * Validate a field. |
||
| 690 | * |
||
| 691 | * @param mixed $value The value to validate. |
||
| 692 | * @param ValidationField $field A validation object to add errors to. |
||
| 693 | * @param bool $sparse Whether or not this is a sparse validation. |
||
| 694 | * @return mixed|Invalid Returns a clean version of the value with all extra fields stripped out or invalid if the value |
||
| 695 | * is completely invalid. |
||
| 696 | */ |
||
| 697 | 142 | protected function validateField($value, ValidationField $field, $sparse = false) { |
|
| 698 | 142 | $result = $value = $this->filterField($value, $field); |
|
| 699 | |||
| 700 | 142 | if ($field->getField() instanceof Schema) { |
|
| 701 | try { |
||
| 702 | 3 | $result = $field->getField()->validate($value, $sparse); |
|
| 703 | 1 | } catch (ValidationException $ex) { |
|
| 704 | // The validation failed, so merge the validations together. |
||
| 705 | 3 | $field->getValidation()->merge($ex->getValidation(), $field->getName()); |
|
| 706 | } |
||
| 707 | 142 | } elseif (($value === null || ($value === '' && !$field->hasType('string'))) && $field->hasType('null')) { |
|
| 708 | 7 | $result = null; |
|
| 709 | } else { |
||
| 710 | // Validate the field's type. |
||
| 711 | 141 | $type = $field->getType(); |
|
| 712 | 141 | if (is_array($type)) { |
|
| 713 | 24 | $result = $this->validateMultipleTypes($value, $type, $field, $sparse); |
|
| 714 | } else { |
||
| 715 | 118 | $result = $this->validateSingleType($value, $type, $field, $sparse); |
|
| 716 | } |
||
| 717 | 141 | if (Invalid::isValid($result)) { |
|
| 718 | 139 | $result = $this->validateEnum($result, $field); |
|
| 719 | } |
||
| 720 | } |
||
| 721 | |||
| 722 | // Validate a custom field validator. |
||
| 723 | 142 | if (Invalid::isValid($result)) { |
|
| 724 | 140 | $this->callValidators($result, $field); |
|
| 725 | } |
||
| 726 | |||
| 727 | 142 | return $result; |
|
| 728 | } |
||
| 729 | |||
| 730 | /** |
||
| 731 | * Validate an array. |
||
| 732 | * |
||
| 733 | * @param mixed $value The value to validate. |
||
| 734 | * @param ValidationField $field The validation results to add. |
||
| 735 | * @param bool $sparse Whether or not this is a sparse validation. |
||
| 736 | * @return array|Invalid Returns an array or invalid if validation fails. |
||
| 737 | */ |
||
| 738 | 20 | protected function validateArray($value, ValidationField $field, $sparse = false) { |
|
| 739 | 20 | if ((!is_array($value) || (count($value) > 0 && !array_key_exists(0, $value))) && !$value instanceof \Traversable) { |
|
| 740 | 5 | $field->addTypeError('array'); |
|
| 741 | 5 | return Invalid::value(); |
|
| 742 | } else { |
||
| 743 | 16 | if ((null !== $minItems = $field->val('minItems')) && count($value) < $minItems) { |
|
| 744 | 1 | $field->addError( |
|
| 745 | 1 | 'minItems', |
|
| 746 | [ |
||
| 747 | 1 | 'messageCode' => '{field} must contain at least {minItems} {minItems,plural,item}.', |
|
| 748 | 1 | 'minItems' => $minItems, |
|
| 749 | 1 | 'status' => 422 |
|
| 750 | ] |
||
| 751 | ); |
||
| 752 | } |
||
| 753 | 16 | if ((null !== $maxItems = $field->val('maxItems')) && count($value) > $maxItems) { |
|
| 754 | 1 | $field->addError( |
|
| 755 | 1 | 'maxItems', |
|
| 756 | [ |
||
| 757 | 1 | 'messageCode' => '{field} must contain no more than {maxItems} {maxItems,plural,item}.', |
|
| 758 | 1 | 'maxItems' => $maxItems, |
|
| 759 | 1 | 'status' => 422 |
|
| 760 | ] |
||
| 761 | ); |
||
| 762 | } |
||
| 763 | |||
| 764 | 16 | if ($field->val('items') !== null) { |
|
| 765 | 12 | $result = []; |
|
| 766 | |||
| 767 | // Validate each of the types. |
||
| 768 | 12 | $itemValidation = new ValidationField( |
|
| 769 | 12 | $field->getValidation(), |
|
| 770 | 12 | $field->val('items'), |
|
| 771 | 12 | '', |
|
| 772 | 12 | $sparse |
|
| 773 | ); |
||
| 774 | |||
| 775 | 12 | $count = 0; |
|
| 776 | 12 | foreach ($value as $i => $item) { |
|
| 777 | 12 | $itemValidation->setName($field->getName()."[{$i}]"); |
|
| 778 | 12 | $validItem = $this->validateField($item, $itemValidation, $sparse); |
|
| 779 | 12 | if (Invalid::isValid($validItem)) { |
|
| 780 | 12 | $result[] = $validItem; |
|
| 781 | } |
||
| 782 | 12 | $count++; |
|
| 783 | } |
||
| 784 | |||
| 785 | 12 | return empty($result) && $count > 0 ? Invalid::value() : $result; |
|
| 786 | } else { |
||
| 787 | // Cast the items into a proper numeric array. |
||
| 788 | 4 | $result = is_array($value) ? array_values($value) : iterator_to_array($value); |
|
| 789 | 4 | return $result; |
|
| 790 | } |
||
| 791 | } |
||
| 792 | } |
||
| 793 | |||
| 794 | /** |
||
| 795 | * Validate a boolean value. |
||
| 796 | * |
||
| 797 | * @param mixed $value The value to validate. |
||
| 798 | * @param ValidationField $field The validation results to add. |
||
| 799 | * @return bool|Invalid Returns the cleaned value or invalid if validation fails. |
||
| 800 | */ |
||
| 801 | 27 | protected function validateBoolean($value, ValidationField $field) { |
|
| 810 | |||
| 811 | /** |
||
| 812 | * Validate a date time. |
||
| 813 | * |
||
| 814 | * @param mixed $value The value to validate. |
||
| 815 | * @param ValidationField $field The validation results to add. |
||
| 816 | * @return \DateTimeInterface|Invalid Returns the cleaned value or **null** if it isn't valid. |
||
| 817 | */ |
||
| 818 | 11 | protected function validateDatetime($value, ValidationField $field) { |
|
| 819 | 11 | if ($value instanceof \DateTimeInterface) { |
|
| 820 | // do nothing, we're good |
||
| 821 | 10 | } elseif (is_string($value) && $value !== '' && !is_numeric($value)) { |
|
| 822 | try { |
||
| 823 | 7 | $dt = new \DateTimeImmutable($value); |
|
| 824 | 6 | if ($dt) { |
|
| 825 | 6 | $value = $dt; |
|
| 826 | } else { |
||
| 827 | 6 | $value = null; |
|
| 828 | } |
||
| 829 | 1 | } catch (\Exception $ex) { |
|
| 830 | 7 | $value = Invalid::value(); |
|
| 831 | } |
||
| 832 | 3 | } elseif (is_int($value) && $value > 0) { |
|
| 833 | 1 | $value = new \DateTimeImmutable('@'.(string)round($value)); |
|
| 834 | } else { |
||
| 835 | 2 | $value = Invalid::value(); |
|
| 836 | } |
||
| 837 | |||
| 838 | 11 | if (Invalid::isInvalid($value)) { |
|
| 839 | 3 | $field->addTypeError('datetime'); |
|
| 840 | } |
||
| 841 | 11 | return $value; |
|
| 842 | } |
||
| 843 | |||
| 844 | /** |
||
| 845 | * Validate a float. |
||
| 846 | * |
||
| 847 | * @param mixed $value The value to validate. |
||
| 848 | * @param ValidationField $field The validation results to add. |
||
| 849 | * @return float|Invalid Returns a number or **null** if validation fails. |
||
| 850 | */ |
||
| 851 | 10 | protected function validateNumber($value, ValidationField $field) { |
|
| 859 | /** |
||
| 860 | * Validate and integer. |
||
| 861 | * |
||
| 862 | * @param mixed $value The value to validate. |
||
| 863 | * @param ValidationField $field The validation results to add. |
||
| 864 | * @return int|Invalid Returns the cleaned value or **null** if validation fails. |
||
| 865 | */ |
||
| 866 | 34 | protected function validateInteger($value, ValidationField $field) { |
|
| 875 | |||
| 876 | /** |
||
| 877 | * Validate an object. |
||
| 878 | * |
||
| 879 | * @param mixed $value The value to validate. |
||
| 880 | * @param ValidationField $field The validation results to add. |
||
| 881 | * @param bool $sparse Whether or not this is a sparse validation. |
||
| 882 | * @return object|Invalid Returns a clean object or **null** if validation fails. |
||
| 883 | */ |
||
| 884 | 80 | protected function validateObject($value, ValidationField $field, $sparse = false) { |
|
| 885 | 80 | if (!$this->isArray($value) || isset($value[0])) { |
|
| 886 | 5 | $field->addTypeError('object'); |
|
| 887 | 5 | return Invalid::value(); |
|
| 888 | 80 | } elseif (is_array($field->val('properties'))) { |
|
| 889 | // Validate the data against the internal schema. |
||
| 890 | 77 | $value = $this->validateProperties($value, $field, $sparse); |
|
| 891 | 3 | } elseif (!is_array($value)) { |
|
| 892 | 3 | $value = $this->toObjectArray($value); |
|
| 893 | } |
||
| 894 | 78 | return $value; |
|
| 895 | } |
||
| 896 | |||
| 897 | /** |
||
| 898 | * Validate data against the schema and return the result. |
||
| 899 | * |
||
| 900 | * @param array|\ArrayAccess $data The data to validate. |
||
| 901 | * @param ValidationField $field This argument will be filled with the validation result. |
||
| 902 | * @param bool $sparse Whether or not this is a sparse validation. |
||
| 903 | * @return array|Invalid Returns a clean array with only the appropriate properties and the data coerced to proper types. |
||
| 904 | * or invalid if there are no valid properties. |
||
| 905 | */ |
||
| 906 | 77 | protected function validateProperties($data, ValidationField $field, $sparse = false) { |
|
| 907 | 77 | $properties = $field->val('properties', []); |
|
| 908 | 77 | $required = array_flip($field->val('required', [])); |
|
| 909 | |||
| 910 | 77 | if (is_array($data)) { |
|
| 911 | 73 | $keys = array_keys($data); |
|
| 912 | 73 | $clean = []; |
|
| 913 | } else { |
||
| 914 | 4 | $keys = array_keys(iterator_to_array($data)); |
|
| 915 | 4 | $class = get_class($data); |
|
| 916 | 4 | $clean = new $class; |
|
| 917 | |||
| 918 | 4 | if ($clean instanceof \ArrayObject) { |
|
| 919 | 3 | $clean->setFlags($data->getFlags()); |
|
| 920 | 3 | $clean->setIteratorClass($data->getIteratorClass()); |
|
| 921 | } |
||
| 922 | } |
||
| 923 | 77 | $keys = array_combine(array_map('strtolower', $keys), $keys); |
|
| 924 | |||
| 925 | 77 | $propertyField = new ValidationField($field->getValidation(), [], null, $sparse); |
|
| 926 | |||
| 927 | // Loop through the schema fields and validate each one. |
||
| 928 | 77 | foreach ($properties as $propertyName => $property) { |
|
| 929 | $propertyField |
||
| 930 | 77 | ->setField($property) |
|
| 931 | 77 | ->setName(ltrim($field->getName().".$propertyName", '.')); |
|
| 932 | |||
| 933 | 77 | $lName = strtolower($propertyName); |
|
| 934 | 77 | $isRequired = isset($required[$propertyName]); |
|
| 935 | |||
| 936 | // First check for required fields. |
||
| 937 | 77 | if (!array_key_exists($lName, $keys)) { |
|
| 938 | 18 | if ($sparse) { |
|
| 939 | // Sparse validation can leave required fields out. |
||
| 940 | 17 | } elseif ($propertyField->hasVal('default')) { |
|
| 941 | 2 | $clean[$propertyName] = $propertyField->val('default'); |
|
| 942 | 15 | } elseif ($isRequired) { |
|
| 943 | 18 | $propertyField->addError('missingField', ['messageCode' => '{field} is required.']); |
|
| 944 | } |
||
| 945 | } else { |
||
| 946 | 74 | $value = $data[$keys[$lName]]; |
|
| 947 | |||
| 948 | 74 | if (in_array($value, [null, ''], true) && !$isRequired && !$propertyField->hasType('null')) { |
|
| 949 | 5 | if ($propertyField->getType() !== 'string' || $value === null) { |
|
| 950 | 2 | continue; |
|
| 951 | } |
||
| 952 | } |
||
| 953 | |||
| 954 | 72 | $clean[$propertyName] = $this->validateField($value, $propertyField, $sparse); |
|
| 955 | } |
||
| 956 | |||
| 957 | 75 | unset($keys[$lName]); |
|
| 958 | } |
||
| 959 | |||
| 960 | // Look for extraneous properties. |
||
| 961 | 77 | if (!empty($keys)) { |
|
| 962 | 9 | if ($this->hasFlag(Schema::VALIDATE_EXTRA_PROPERTY_NOTICE)) { |
|
| 963 | 2 | $msg = sprintf("%s has unexpected field(s): %s.", $field->getName() ?: 'value', implode(', ', $keys)); |
|
| 964 | 2 | trigger_error($msg, E_USER_NOTICE); |
|
| 965 | } |
||
| 966 | |||
| 967 | 7 | if ($this->hasFlag(Schema::VALIDATE_EXTRA_PROPERTY_EXCEPTION)) { |
|
| 968 | 2 | $field->addError('invalid', [ |
|
| 969 | 2 | 'messageCode' => '{field} has {extra,plural,an unexpected field,unexpected fields}: {extra}.', |
|
| 970 | 2 | 'extra' => array_values($keys), |
|
| 971 | 2 | 'status' => 422 |
|
| 972 | ]); |
||
| 973 | } |
||
| 974 | } |
||
| 975 | |||
| 976 | 75 | return $clean; |
|
| 977 | } |
||
| 978 | |||
| 979 | /** |
||
| 980 | * Validate a string. |
||
| 981 | * |
||
| 982 | * @param mixed $value The value to validate. |
||
| 983 | * @param ValidationField $field The validation results to add. |
||
| 984 | * @return string|Invalid Returns the valid string or **null** if validation fails. |
||
| 985 | */ |
||
| 986 | 61 | protected function validateString($value, ValidationField $field) { |
|
| 987 | 61 | if (is_string($value) || is_numeric($value)) { |
|
| 988 | 59 | $value = $result = (string)$value; |
|
| 989 | } else { |
||
| 990 | 4 | $field->addTypeError('string'); |
|
| 991 | 4 | return Invalid::value(); |
|
| 992 | } |
||
| 993 | |||
| 994 | 59 | $errorCount = $field->getErrorCount(); |
|
| 995 | 59 | if (($minLength = $field->val('minLength', 0)) > 0 && mb_strlen($value) < $minLength) { |
|
| 996 | 3 | if (!empty($field->getName()) && $minLength === 1) { |
|
| 997 | 1 | $field->addError('missingField', ['messageCode' => '{field} is required.', 'status' => 422]); |
|
| 998 | } else { |
||
| 999 | 2 | $field->addError( |
|
| 1000 | 2 | 'minLength', |
|
| 1001 | [ |
||
| 1002 | 2 | 'messageCode' => '{field} should be at least {minLength} {minLength,plural,character} long.', |
|
| 1003 | 2 | 'minLength' => $minLength, |
|
| 1004 | 2 | 'status' => 422 |
|
| 1005 | ] |
||
| 1006 | ); |
||
| 1007 | } |
||
| 1008 | } |
||
| 1009 | 59 | if (($maxLength = $field->val('maxLength', 0)) > 0 && mb_strlen($value) > $maxLength) { |
|
| 1010 | 1 | $field->addError( |
|
| 1011 | 1 | 'maxLength', |
|
| 1012 | [ |
||
| 1013 | 1 | 'messageCode' => '{field} is {overflow} {overflow,plural,characters} too long.', |
|
| 1014 | 1 | 'maxLength' => $maxLength, |
|
| 1015 | 1 | 'overflow' => mb_strlen($value) - $maxLength, |
|
| 1016 | 1 | 'status' => 422 |
|
| 1017 | ] |
||
| 1018 | ); |
||
| 1019 | } |
||
| 1020 | 59 | if ($pattern = $field->val('pattern')) { |
|
| 1021 | 4 | $regex = '`'.str_replace('`', preg_quote('`', '`'), $pattern).'`'; |
|
| 1022 | |||
| 1023 | 4 | if (!preg_match($regex, $value)) { |
|
| 1024 | 2 | $field->addError( |
|
| 1025 | 2 | 'invalid', |
|
| 1026 | [ |
||
| 1027 | 2 | 'messageCode' => '{field} is in the incorrect format.', |
|
| 1028 | 'status' => 422 |
||
| 1029 | ] |
||
| 1030 | ); |
||
| 1031 | } |
||
| 1032 | } |
||
| 1033 | 59 | if ($format = $field->val('format')) { |
|
| 1034 | 15 | $type = $format; |
|
| 1035 | switch ($format) { |
||
| 1036 | 15 | case 'date-time': |
|
| 1037 | 4 | $result = $this->validateDatetime($result, $field); |
|
| 1038 | 4 | if ($result instanceof \DateTimeInterface) { |
|
| 1039 | 4 | $result = $result->format(\DateTime::RFC3339); |
|
| 1040 | } |
||
| 1041 | 4 | break; |
|
| 1042 | 11 | case 'email': |
|
| 1043 | 1 | $result = filter_var($result, FILTER_VALIDATE_EMAIL); |
|
| 1044 | 1 | break; |
|
| 1045 | 10 | case 'ipv4': |
|
| 1046 | 1 | $type = 'IPv4 address'; |
|
| 1047 | 1 | $result = filter_var($result, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4); |
|
| 1048 | 1 | break; |
|
| 1049 | 9 | case 'ipv6': |
|
| 1050 | 1 | $type = 'IPv6 address'; |
|
| 1051 | 1 | $result = filter_var($result, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6); |
|
| 1052 | 1 | break; |
|
| 1053 | 8 | case 'ip': |
|
| 1054 | 1 | $type = 'IP address'; |
|
| 1055 | 1 | $result = filter_var($result, FILTER_VALIDATE_IP); |
|
| 1056 | 1 | break; |
|
| 1057 | 7 | case 'uri': |
|
| 1058 | 7 | $type = 'URI'; |
|
| 1059 | 7 | $result = filter_var($result, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED | FILTER_FLAG_SCHEME_REQUIRED); |
|
| 1060 | 7 | break; |
|
| 1061 | default: |
||
| 1062 | trigger_error("Unrecognized format '$format'.", E_USER_NOTICE); |
||
| 1063 | } |
||
| 1064 | 15 | if ($result === false) { |
|
| 1065 | 5 | $field->addTypeError($type); |
|
| 1066 | } |
||
| 1067 | } |
||
| 1068 | |||
| 1069 | 59 | if ($field->isValid()) { |
|
| 1070 | 52 | return $result; |
|
| 1071 | } else { |
||
| 1072 | 11 | return Invalid::value(); |
|
| 1073 | } |
||
| 1074 | } |
||
| 1075 | |||
| 1076 | /** |
||
| 1077 | * Validate a unix timestamp. |
||
| 1078 | * |
||
| 1079 | * @param mixed $value The value to validate. |
||
| 1080 | * @param ValidationField $field The field being validated. |
||
| 1081 | * @return int|Invalid Returns a valid timestamp or invalid if the value doesn't validate. |
||
| 1082 | */ |
||
| 1083 | 5 | protected function validateTimestamp($value, ValidationField $field) { |
|
| 1084 | 5 | if (is_numeric($value) && $value > 0) { |
|
| 1085 | 1 | $result = (int)$value; |
|
| 1086 | 4 | } elseif (is_string($value) && $ts = strtotime($value)) { |
|
| 1087 | 1 | $result = $ts; |
|
| 1088 | } else { |
||
| 1089 | 3 | $field->addTypeError('timestamp'); |
|
| 1090 | 3 | $result = Invalid::value(); |
|
| 1091 | } |
||
| 1092 | 5 | return $result; |
|
| 1093 | } |
||
| 1094 | |||
| 1095 | /** |
||
| 1096 | * Validate a null value. |
||
| 1097 | * |
||
| 1098 | * @param mixed $value The value to validate. |
||
| 1099 | * @param ValidationField $field The error collector for the field. |
||
| 1100 | * @return null|Invalid Returns **null** or invalid. |
||
| 1101 | */ |
||
| 1102 | 1 | protected function validateNull($value, ValidationField $field) { |
|
| 1103 | 1 | if ($value === null) { |
|
| 1104 | return null; |
||
| 1105 | } |
||
| 1106 | 1 | $field->addError('invalid', ['messageCode' => '{field} should be null.', 'status' => 422]); |
|
| 1107 | 1 | return Invalid::value(); |
|
| 1108 | } |
||
| 1109 | |||
| 1110 | /** |
||
| 1111 | * Validate a value against an enum. |
||
| 1112 | * |
||
| 1113 | * @param mixed $value The value to test. |
||
| 1114 | * @param ValidationField $field The validation object for adding errors. |
||
| 1115 | * @return mixed|Invalid Returns the value if it is one of the enumerated values or invalid otherwise. |
||
| 1116 | */ |
||
| 1117 | 139 | protected function validateEnum($value, ValidationField $field) { |
|
| 1118 | 139 | $enum = $field->val('enum'); |
|
| 1119 | 139 | if (empty($enum)) { |
|
| 1120 | 138 | return $value; |
|
| 1121 | } |
||
| 1122 | |||
| 1123 | 1 | if (!in_array($value, $enum, true)) { |
|
| 1124 | 1 | $field->addError( |
|
| 1125 | 1 | 'invalid', |
|
| 1126 | [ |
||
| 1127 | 1 | 'messageCode' => '{field} must be one of: {enum}.', |
|
| 1128 | 1 | 'enum' => $enum, |
|
| 1129 | 1 | 'status' => 422 |
|
| 1130 | ] |
||
| 1131 | ); |
||
| 1132 | 1 | return Invalid::value(); |
|
| 1133 | } |
||
| 1134 | 1 | return $value; |
|
| 1135 | } |
||
| 1136 | |||
| 1137 | /** |
||
| 1138 | * Call all of the filters attached to a field. |
||
| 1139 | * |
||
| 1140 | * @param mixed $value The field value being filtered. |
||
| 1141 | * @param ValidationField $field The validation object. |
||
| 1142 | * @return mixed Returns the filtered value. If there are no filters for the field then the original value is returned. |
||
| 1143 | */ |
||
| 1144 | 142 | protected function callFilters($value, ValidationField $field) { |
|
| 1145 | // Strip array references in the name except for the last one. |
||
| 1146 | 142 | $key = preg_replace(['`\[\d+\]$`', '`\[\d+\]`'], ['[]', ''], $field->getName()); |
|
| 1147 | 142 | if (!empty($this->filters[$key])) { |
|
| 1148 | 1 | foreach ($this->filters[$key] as $filter) { |
|
| 1149 | 1 | $value = call_user_func($filter, $value, $field); |
|
| 1150 | } |
||
| 1151 | } |
||
| 1152 | 142 | return $value; |
|
| 1153 | } |
||
| 1154 | |||
| 1155 | /** |
||
| 1156 | * Call all of the validators attached to a field. |
||
| 1157 | * |
||
| 1158 | * @param mixed $value The field value being validated. |
||
| 1159 | * @param ValidationField $field The validation object to add errors. |
||
| 1160 | */ |
||
| 1161 | 140 | protected function callValidators($value, ValidationField $field) { |
|
| 1162 | 140 | $valid = true; |
|
| 1163 | |||
| 1164 | // Strip array references in the name except for the last one. |
||
| 1165 | 140 | $key = preg_replace(['`\[\d+\]$`', '`\[\d+\]`'], ['[]', ''], $field->getName()); |
|
| 1166 | 140 | if (!empty($this->validators[$key])) { |
|
| 1167 | 4 | foreach ($this->validators[$key] as $validator) { |
|
| 1168 | 4 | $r = call_user_func($validator, $value, $field); |
|
| 1169 | |||
| 1170 | 4 | if ($r === false || Invalid::isInvalid($r)) { |
|
| 1171 | 4 | $valid = false; |
|
| 1172 | } |
||
| 1173 | } |
||
| 1174 | } |
||
| 1175 | |||
| 1176 | // Add an error on the field if the validator hasn't done so. |
||
| 1177 | 140 | if (!$valid && $field->isValid()) { |
|
| 1178 | $field->addError('invalid', ['messageCode' => '{field} is invalid.', 'status' => 422]); |
||
| 1179 | } |
||
| 1180 | 140 | } |
|
| 1181 | |||
| 1182 | /** |
||
| 1183 | * Specify data which should be serialized to JSON. |
||
| 1184 | * |
||
| 1185 | * This method specifically returns data compatible with the JSON schema format. |
||
| 1186 | * |
||
| 1187 | * @return mixed Returns data which can be serialized by **json_encode()**, which is a value of any type other than a resource. |
||
| 1188 | * @link http://php.net/manual/en/jsonserializable.jsonserialize.php |
||
| 1189 | * @link http://json-schema.org/ |
||
| 1190 | */ |
||
| 1191 | public function jsonSerialize() { |
||
| 1192 | 14 | $fix = function ($schema) use (&$fix) { |
|
| 1193 | 14 | if ($schema instanceof Schema) { |
|
| 1194 | 1 | return $schema->jsonSerialize(); |
|
| 1195 | } |
||
| 1196 | |||
| 1197 | 14 | if (!empty($schema['type'])) { |
|
| 1198 | // Swap datetime and timestamp to other types with formats. |
||
| 1199 | 13 | if ($schema['type'] === 'datetime') { |
|
| 1200 | 3 | $schema['type'] = 'string'; |
|
| 1201 | 3 | $schema['format'] = 'date-time'; |
|
| 1202 | 12 | } elseif ($schema['type'] === 'timestamp') { |
|
| 1203 | 3 | $schema['type'] = 'integer'; |
|
| 1204 | 3 | $schema['format'] = 'timestamp'; |
|
| 1205 | } |
||
| 1206 | } |
||
| 1207 | |||
| 1208 | 14 | if (!empty($schema['items'])) { |
|
| 1209 | 4 | $schema['items'] = $fix($schema['items']); |
|
| 1210 | } |
||
| 1211 | 14 | if (!empty($schema['properties'])) { |
|
| 1212 | 10 | $properties = []; |
|
| 1213 | 10 | foreach ($schema['properties'] as $key => $property) { |
|
| 1214 | 10 | $properties[$key] = $fix($property); |
|
| 1215 | } |
||
| 1216 | 10 | $schema['properties'] = $properties; |
|
| 1217 | } |
||
| 1218 | |||
| 1219 | 14 | return $schema; |
|
| 1220 | 14 | }; |
|
| 1221 | |||
| 1222 | 14 | $result = $fix($this->schema); |
|
| 1223 | |||
| 1224 | 14 | return $result; |
|
| 1225 | } |
||
| 1226 | |||
| 1227 | /** |
||
| 1228 | * Look up a type based on its alias. |
||
| 1229 | * |
||
| 1230 | * @param string $alias The type alias or type name to lookup. |
||
| 1231 | * @return mixed |
||
| 1232 | */ |
||
| 1233 | 132 | protected function getType($alias) { |
|
| 1234 | 132 | if (isset(self::$types[$alias])) { |
|
| 1235 | return $alias; |
||
| 1236 | } |
||
| 1237 | 132 | foreach (self::$types as $type => $aliases) { |
|
| 1238 | 132 | if (in_array($alias, $aliases, true)) { |
|
| 1239 | 132 | return $type; |
|
| 1240 | } |
||
| 1241 | } |
||
| 1242 | 6 | return null; |
|
| 1243 | } |
||
| 1244 | |||
| 1245 | /** |
||
| 1246 | * Get the class that's used to contain validation information. |
||
| 1247 | * |
||
| 1248 | * @return Validation|string Returns the validation class. |
||
| 1249 | */ |
||
| 1250 | 142 | public function getValidationClass() { |
|
| 1253 | |||
| 1254 | /** |
||
| 1255 | * Set the class that's used to contain validation information. |
||
| 1256 | * |
||
| 1257 | * @param Validation|string $class Either the name of a class or a class that will be cloned. |
||
| 1258 | * @return $this |
||
| 1259 | */ |
||
| 1260 | 1 | public function setValidationClass($class) { |
|
| 1268 | |||
| 1269 | /** |
||
| 1270 | * Create a new validation instance. |
||
| 1271 | * |
||
| 1272 | * @return Validation Returns a validation object. |
||
| 1273 | */ |
||
| 1274 | 142 | protected function createValidation() { |
|
| 1275 | 142 | $class = $this->getValidationClass(); |
|
| 1276 | |||
| 1277 | 142 | if ($class instanceof Validation) { |
|
| 1278 | 1 | $result = clone $class; |
|
| 1279 | } else { |
||
| 1280 | 142 | $result = new $class; |
|
| 1281 | } |
||
| 1282 | 142 | return $result; |
|
| 1283 | } |
||
| 1284 | |||
| 1285 | /** |
||
| 1286 | * Check whether or not a value is an array or accessible like an array. |
||
| 1287 | * |
||
| 1288 | * @param mixed $value The value to check. |
||
| 1289 | * @return bool Returns **true** if the value can be used like an array or **false** otherwise. |
||
| 1290 | */ |
||
| 1291 | 80 | private function isArray($value) { |
|
| 1294 | |||
| 1295 | /** |
||
| 1296 | * Cast a value to an array. |
||
| 1297 | * |
||
| 1298 | * @param \Traversable $value The value to convert. |
||
| 1299 | * @return array Returns an array. |
||
| 1300 | */ |
||
| 1301 | 3 | private function toObjectArray(\Traversable $value) { |
|
| 1302 | 3 | $class = get_class($value); |
|
| 1303 | 3 | if ($value instanceof \ArrayObject) { |
|
| 1304 | 2 | return new $class($value->getArrayCopy(), $value->getFlags(), $value->getIteratorClass()); |
|
| 1305 | 1 | } elseif ($value instanceof \ArrayAccess) { |
|
| 1306 | 1 | $r = new $class; |
|
| 1307 | 1 | foreach ($value as $k => $v) { |
|
| 1308 | 1 | $r[$k] = $v; |
|
| 1309 | } |
||
| 1310 | 1 | return $r; |
|
| 1311 | } |
||
| 1312 | return iterator_to_array($value); |
||
| 1313 | } |
||
| 1314 | |||
| 1315 | /** |
||
| 1316 | * Return a sparse version of this schema. |
||
| 1317 | * |
||
| 1318 | * A sparse schema has no required properties. |
||
| 1319 | * |
||
| 1320 | * @return Schema Returns a new sparse schema. |
||
| 1321 | */ |
||
| 1322 | 2 | public function withSparse() { |
|
| 1326 | |||
| 1327 | /** |
||
| 1328 | * The internal implementation of `Schema::withSparse()`. |
||
| 1329 | * |
||
| 1330 | * @param array|Schema $schema The schema to make sparse. |
||
| 1331 | * @param \SplObjectStorage $schemas Collected sparse schemas that have already been made. |
||
| 1332 | * @return mixed |
||
| 1333 | */ |
||
| 1334 | 2 | private function withSparseInternal($schema, \SplObjectStorage $schemas) { |
|
| 1335 | 2 | if ($schema instanceof Schema) { |
|
| 1336 | 2 | if ($schemas->contains($schema)) { |
|
| 1337 | 1 | return $schemas[$schema]; |
|
| 1338 | } else { |
||
| 1339 | 2 | $schemas[$schema] = $sparseSchema = new Schema(); |
|
| 1340 | 2 | $sparseSchema->schema = $schema->withSparseInternal($schema->schema, $schemas); |
|
| 1341 | 2 | if ($id = $sparseSchema->getID()) { |
|
| 1342 | $sparseSchema->setID($id.'Sparse'); |
||
| 1343 | } |
||
| 1344 | |||
| 1345 | 2 | return $sparseSchema; |
|
| 1346 | } |
||
| 1347 | } |
||
| 1348 | |||
| 1349 | 2 | unset($schema['required']); |
|
| 1350 | |||
| 1351 | 2 | if (isset($schema['items'])) { |
|
| 1352 | 1 | $schema['items'] = $this->withSparseInternal($schema['items'], $schemas); |
|
| 1353 | } |
||
| 1354 | 2 | if (isset($schema['properties'])) { |
|
| 1355 | 2 | foreach ($schema['properties'] as $name => &$property) { |
|
| 1356 | 2 | $property = $this->withSparseInternal($property, $schemas); |
|
| 1357 | } |
||
| 1358 | } |
||
| 1359 | |||
| 1360 | 2 | return $schema; |
|
| 1361 | } |
||
| 1362 | |||
| 1363 | /** |
||
| 1364 | * Filter a field's value using built in and custom filters. |
||
| 1365 | * |
||
| 1366 | * @param mixed $value The original value of the field. |
||
| 1367 | * @param ValidationField $field The field information for the field. |
||
| 1368 | * @return mixed Returns the filtered field or the original field value if there are no filters. |
||
| 1369 | */ |
||
| 1370 | 142 | private function filterField($value, ValidationField $field) { |
|
| 1371 | // Check for limited support for Open API style. |
||
| 1372 | 142 | if (!empty($field->val('style')) && is_string($value)) { |
|
| 1373 | 8 | $doFilter = true; |
|
| 1374 | 8 | if ($field->hasType('boolean') && in_array($value, ['true', 'false', '0', '1'], true)) { |
|
| 1375 | 4 | $doFilter = false; |
|
| 1376 | 4 | } elseif ($field->hasType('integer') || $field->hasType('number') && is_numeric($value)) { |
|
| 1377 | $doFilter = false; |
||
| 1378 | } |
||
| 1379 | |||
| 1380 | 8 | if ($doFilter) { |
|
| 1381 | 4 | switch ($field->val('style')) { |
|
| 1382 | 4 | case 'form': |
|
| 1383 | 2 | $value = explode(',', $value); |
|
| 1384 | 2 | break; |
|
| 1385 | 2 | case 'spaceDelimited': |
|
| 1386 | 1 | $value = explode(' ', $value); |
|
| 1387 | 1 | break; |
|
| 1388 | 1 | case 'pipeDelimited': |
|
| 1389 | 1 | $value = explode('|', $value); |
|
| 1390 | 1 | break; |
|
| 1391 | } |
||
| 1392 | } |
||
| 1393 | } |
||
| 1394 | |||
| 1395 | 142 | $value = $this->callFilters($value, $field); |
|
| 1396 | |||
| 1397 | 142 | return $value; |
|
| 1398 | } |
||
| 1399 | |||
| 1400 | /** |
||
| 1401 | * Whether a offset exists. |
||
| 1402 | * |
||
| 1403 | * @param mixed $offset An offset to check for. |
||
| 1404 | * @return boolean true on success or false on failure. |
||
| 1405 | * @link http://php.net/manual/en/arrayaccess.offsetexists.php |
||
| 1406 | */ |
||
| 1407 | 4 | public function offsetExists($offset) { |
|
| 1410 | |||
| 1411 | /** |
||
| 1412 | * Offset to retrieve. |
||
| 1413 | * |
||
| 1414 | * @param mixed $offset The offset to retrieve. |
||
| 1415 | * @return mixed Can return all value types. |
||
| 1416 | * @link http://php.net/manual/en/arrayaccess.offsetget.php |
||
| 1417 | */ |
||
| 1418 | 2 | public function offsetGet($offset) { |
|
| 1419 | 2 | return isset($this->schema[$offset]) ? $this->schema[$offset] : null; |
|
| 1420 | } |
||
| 1421 | |||
| 1422 | /** |
||
| 1423 | * Offset to set. |
||
| 1424 | * |
||
| 1425 | * @param mixed $offset The offset to assign the value to. |
||
| 1426 | * @param mixed $value The value to set. |
||
| 1427 | * @link http://php.net/manual/en/arrayaccess.offsetset.php |
||
| 1428 | */ |
||
| 1429 | 1 | public function offsetSet($offset, $value) { |
|
| 1430 | 1 | $this->schema[$offset] = $value; |
|
| 1432 | |||
| 1433 | /** |
||
| 1434 | * Offset to unset. |
||
| 1435 | * |
||
| 1436 | * @param mixed $offset The offset to unset. |
||
| 1437 | * @link http://php.net/manual/en/arrayaccess.offsetunset.php |
||
| 1438 | */ |
||
| 1439 | 1 | public function offsetUnset($offset) { |
|
| 1442 | |||
| 1443 | /** |
||
| 1444 | * Validate a field against a single type. |
||
| 1445 | * |
||
| 1446 | * @param mixed $value The value to validate. |
||
| 1447 | * @param string $type The type to validate against. |
||
| 1448 | * @param ValidationField $field Contains field and validation information. |
||
| 1449 | * @param bool $sparse Whether or not this should be a sparse validation. |
||
| 1450 | * @return mixed Returns the valid value or `Invalid`. |
||
| 1451 | */ |
||
| 1452 | 141 | protected function validateSingleType($value, $type, ValidationField $field, $sparse) { |
|
| 1490 | |||
| 1491 | /** |
||
| 1492 | * Validate a field against multiple basic types. |
||
| 1493 | * |
||
| 1494 | * The first validation that passes will be returned. If no type can be validated against then validation will fail. |
||
| 1495 | * |
||
| 1496 | * @param mixed $value The value to validate. |
||
| 1497 | * @param string[] $types The types to validate against. |
||
| 1498 | * @param ValidationField $field Contains field and validation information. |
||
| 1499 | * @param bool $sparse Whether or not this should be a sparse validation. |
||
| 1500 | * @return mixed Returns the valid value or `Invalid`. |
||
| 1501 | */ |
||
| 1502 | 24 | private function validateMultipleTypes($value, array $types, ValidationField $field, $sparse) { |
|
| 1565 | } |
||
| 1566 |
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.