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 | 155 | 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) { |
|
95 | |||
96 | /** |
||
97 | * Get a schema field. |
||
98 | * |
||
99 | * @param string|array $path The JSON schema path of the field with parts separated by dots. |
||
100 | * @param mixed $default The value to return if the field isn't found. |
||
101 | * @return mixed Returns the field value or `$default`. |
||
102 | */ |
||
103 | 4 | public function getField($path, $default = null) { |
|
122 | |||
123 | /** |
||
124 | * Set a schema field. |
||
125 | * |
||
126 | * @param string|array $path The JSON schema path of the field with parts separated by dots. |
||
127 | * @param mixed $value The new value. |
||
128 | * @return $this |
||
129 | */ |
||
130 | 3 | public function setField($path, $value) { |
|
131 | 3 | if (is_string($path)) { |
|
132 | 3 | $path = explode('.', $path); |
|
133 | 3 | } |
|
134 | |||
135 | 3 | $selection = &$this->schema; |
|
136 | 3 | foreach ($path as $i => $subSelector) { |
|
137 | 3 | if (is_array($selection)) { |
|
138 | 3 | if (!isset($selection[$subSelector])) { |
|
139 | 1 | $selection[$subSelector] = []; |
|
140 | 1 | } |
|
141 | 3 | } elseif ($selection instanceof Schema) { |
|
142 | 1 | $selection->setField(array_slice($path, $i), $value); |
|
143 | 1 | return $this; |
|
144 | } else { |
||
145 | $selection = [$subSelector => []]; |
||
146 | } |
||
147 | 3 | $selection = &$selection[$subSelector]; |
|
148 | 3 | } |
|
149 | |||
150 | 3 | $selection = $value; |
|
151 | 3 | return $this; |
|
152 | } |
||
153 | |||
154 | /** |
||
155 | * Get the ID for the schema. |
||
156 | * |
||
157 | * @return string |
||
158 | */ |
||
159 | 2 | public function getID() { |
|
160 | 2 | return isset($this->schema['id']) ? $this->schema['id'] : ''; |
|
161 | } |
||
162 | |||
163 | /** |
||
164 | * Set the ID for the schema. |
||
165 | * |
||
166 | * @param string $ID The new ID. |
||
167 | * @throws \InvalidArgumentException Throws an exception when the provided ID is not a string. |
||
168 | * @return Schema |
||
169 | */ |
||
170 | public function setID($ID) { |
||
179 | |||
180 | /** |
||
181 | * Return the validation flags. |
||
182 | * |
||
183 | * @return int Returns a bitwise combination of flags. |
||
184 | */ |
||
185 | 1 | public function getFlags() { |
|
188 | |||
189 | /** |
||
190 | * Set the validation flags. |
||
191 | * |
||
192 | * @param int $flags One or more of the **Schema::FLAG_*** constants. |
||
193 | * @return Schema Returns the current instance for fluent calls. |
||
194 | */ |
||
195 | 8 | public function setFlags($flags) { |
|
203 | |||
204 | /** |
||
205 | * Whether or not the schema has a flag (or combination of flags). |
||
206 | * |
||
207 | * @param int $flag One or more of the **Schema::VALIDATE_*** constants. |
||
208 | * @return bool Returns **true** if all of the flags are set or **false** otherwise. |
||
209 | */ |
||
210 | 8 | public function hasFlag($flag) { |
|
213 | |||
214 | /** |
||
215 | * Set a flag. |
||
216 | * |
||
217 | * @param int $flag One or more of the **Schema::VALIDATE_*** constants. |
||
218 | * @param bool $value Either true or false. |
||
219 | * @return $this |
||
220 | */ |
||
221 | 1 | public function setFlag($flag, $value) { |
|
229 | |||
230 | /** |
||
231 | * Merge a schema with this one. |
||
232 | * |
||
233 | * @param Schema $schema A scheme instance. Its parameters will be merged into the current instance. |
||
234 | * @return $this |
||
235 | */ |
||
236 | 3 | public function merge(Schema $schema) { |
|
240 | |||
241 | /** |
||
242 | * Add another schema to this one. |
||
243 | * |
||
244 | * Adding schemas together is analogous to array addition. When you add a schema it will only add missing information. |
||
245 | * |
||
246 | * @param Schema $schema The schema to add. |
||
247 | * @param bool $addProperties Whether to add properties that don't exist in this schema. |
||
248 | * @return $this |
||
249 | */ |
||
250 | 3 | public function add(Schema $schema, $addProperties = false) { |
|
254 | |||
255 | /** |
||
256 | * The internal implementation of schema merging. |
||
257 | * |
||
258 | * @param array &$target The target of the merge. |
||
259 | * @param array $source The source of the merge. |
||
260 | * @param bool $overwrite Whether or not to replace values. |
||
261 | * @param bool $addProperties Whether or not to add object properties to the target. |
||
262 | * @return array |
||
263 | */ |
||
264 | 6 | private function mergeInternal(array &$target, array $source, $overwrite = true, $addProperties = true) { |
|
316 | |||
317 | // public function overlay(Schema $schema ) |
||
318 | |||
319 | /** |
||
320 | * Returns the internal schema array. |
||
321 | * |
||
322 | * @return array |
||
323 | * @see Schema::jsonSerialize() |
||
324 | */ |
||
325 | 15 | public function getSchemaArray() { |
|
328 | |||
329 | /** |
||
330 | * Parse a short schema and return the associated schema. |
||
331 | * |
||
332 | * @param array $arr The schema array. |
||
333 | * @param mixed ...$args Constructor arguments for the schema instance. |
||
334 | * @return static Returns a new schema. |
||
335 | */ |
||
336 | 150 | public static function parse(array $arr, ...$args) { |
|
341 | |||
342 | /** |
||
343 | * Parse a schema in short form into a full schema array. |
||
344 | * |
||
345 | * @param array $arr The array to parse into a schema. |
||
346 | * @return array The full schema array. |
||
347 | * @throws \InvalidArgumentException Throws an exception when an item in the schema is invalid. |
||
348 | */ |
||
349 | 150 | protected function parseInternal(array $arr) { |
|
381 | |||
382 | /** |
||
383 | * Parse a schema node. |
||
384 | * |
||
385 | * @param array $node The node to parse. |
||
386 | * @param mixed $value Additional information from the node. |
||
387 | * @return array Returns a JSON schema compatible node. |
||
388 | */ |
||
389 | 144 | private function parseNode($node, $value = null) { |
|
439 | |||
440 | /** |
||
441 | * Parse the schema for an object's properties. |
||
442 | * |
||
443 | * @param array $arr An object property schema. |
||
444 | * @return array Returns a schema array suitable to be placed in the **properties** key of a schema. |
||
445 | */ |
||
446 | 92 | private function parseProperties(array $arr) { |
|
472 | |||
473 | /** |
||
474 | * Parse a short parameter string into a full array parameter. |
||
475 | * |
||
476 | * @param string $key The short parameter string to parse. |
||
477 | * @param array $value An array of other information that might help resolve ambiguity. |
||
478 | * @return array Returns an array in the form `[string name, array param, bool required]`. |
||
479 | * @throws \InvalidArgumentException Throws an exception if the short param is not in the correct format. |
||
480 | */ |
||
481 | 144 | public function parseShortParam($key, $value = []) { |
|
539 | |||
540 | /** |
||
541 | * Add a custom validator to to validate the schema. |
||
542 | * |
||
543 | * @param string $fieldname The name of the field to validate, if any. |
||
544 | * |
||
545 | * If you are adding a validator to a deeply nested field then separate the path with dots. |
||
546 | * @param callable $callback The callback to validate with. |
||
547 | * @return Schema Returns `$this` for fluent calls. |
||
548 | */ |
||
549 | 2 | public function addValidator($fieldname, callable $callback) { |
|
553 | |||
554 | /** |
||
555 | * Require one of a given set of fields in the schema. |
||
556 | * |
||
557 | * @param array $required The field names to require. |
||
558 | * @param string $fieldname The name of the field to attach to. |
||
559 | * @param int $count The count of required items. |
||
560 | * @return Schema Returns `$this` for fluent calls. |
||
561 | */ |
||
562 | 1 | public function requireOneOf(array $required, $fieldname = '', $count = 1) { |
|
611 | |||
612 | /** |
||
613 | * Validate data against the schema. |
||
614 | * |
||
615 | * @param mixed $data The data to validate. |
||
616 | * @param bool $sparse Whether or not this is a sparse validation. |
||
617 | * @return mixed Returns a cleaned version of the data. |
||
618 | * @throws ValidationException Throws an exception when the data does not validate against the schema. |
||
619 | */ |
||
620 | 120 | public function validate($data, $sparse = false) { |
|
636 | |||
637 | /** |
||
638 | * Validate data against the schema and return the result. |
||
639 | * |
||
640 | * @param mixed $data The data to validate. |
||
641 | * @param bool $sparse Whether or not to do a sparse validation. |
||
642 | * @return bool Returns true if the data is valid. False otherwise. |
||
643 | */ |
||
644 | 33 | public function isValid($data, $sparse = false) { |
|
652 | |||
653 | /** |
||
654 | * Validate a field. |
||
655 | * |
||
656 | * @param mixed $value The value to validate. |
||
657 | * @param ValidationField $field A validation object to add errors to. |
||
658 | * @param bool $sparse Whether or not this is a sparse validation. |
||
659 | * @return mixed|Invalid Returns a clean version of the value with all extra fields stripped out or invalid if the value |
||
660 | * is completely invalid. |
||
661 | */ |
||
662 | 120 | protected function validateField($value, ValidationField $field, $sparse = false) { |
|
720 | |||
721 | /** |
||
722 | * Validate an array. |
||
723 | * |
||
724 | * @param mixed $value The value to validate. |
||
725 | * @param ValidationField $field The validation results to add. |
||
726 | * @param bool $sparse Whether or not this is a sparse validation. |
||
727 | * @return array|Invalid Returns an array or invalid if validation fails. |
||
728 | */ |
||
729 | 15 | protected function validateArray($value, ValidationField $field, $sparse = false) { |
|
761 | |||
762 | /** |
||
763 | * Validate a boolean value. |
||
764 | * |
||
765 | * @param mixed $value The value to validate. |
||
766 | * @param ValidationField $field The validation results to add. |
||
767 | * @return bool|Invalid Returns the cleaned value or invalid if validation fails. |
||
768 | */ |
||
769 | 21 | protected function validateBoolean($value, ValidationField $field) { |
|
777 | |||
778 | /** |
||
779 | * Validate a date time. |
||
780 | * |
||
781 | * @param mixed $value The value to validate. |
||
782 | * @param ValidationField $field The validation results to add. |
||
783 | * @return \DateTimeInterface|Invalid Returns the cleaned value or **null** if it isn't valid. |
||
784 | */ |
||
785 | 13 | protected function validateDatetime($value, ValidationField $field) { |
|
810 | |||
811 | /** |
||
812 | * Validate a float. |
||
813 | * |
||
814 | * @param mixed $value The value to validate. |
||
815 | * @param ValidationField $field The validation results to add. |
||
816 | * @return float|Invalid Returns a number or **null** if validation fails. |
||
817 | */ |
||
818 | 9 | protected function validateNumber($value, ValidationField $field) { |
|
826 | |||
827 | /** |
||
828 | * Validate and integer. |
||
829 | * |
||
830 | * @param mixed $value The value to validate. |
||
831 | * @param ValidationField $field The validation results to add. |
||
832 | * @return int|Invalid Returns the cleaned value or **null** if validation fails. |
||
833 | */ |
||
834 | 25 | protected function validateInteger($value, ValidationField $field) { |
|
843 | |||
844 | /** |
||
845 | * Validate an object. |
||
846 | * |
||
847 | * @param mixed $value The value to validate. |
||
848 | * @param ValidationField $field The validation results to add. |
||
849 | * @param bool $sparse Whether or not this is a sparse validation. |
||
850 | * @return object|Invalid Returns a clean object or **null** if validation fails. |
||
851 | */ |
||
852 | 80 | protected function validateObject($value, ValidationField $field, $sparse = false) { |
|
864 | |||
865 | /** |
||
866 | * Validate data against the schema and return the result. |
||
867 | * |
||
868 | * @param array|\ArrayAccess $data The data to validate. |
||
869 | * @param ValidationField $field This argument will be filled with the validation result. |
||
870 | * @param bool $sparse Whether or not this is a sparse validation. |
||
871 | * @return array|Invalid Returns a clean array with only the appropriate properties and the data coerced to proper types. |
||
872 | * or invalid if there are no valid properties. |
||
873 | */ |
||
874 | 79 | protected function validateProperties($data, ValidationField $field, $sparse = false) { |
|
931 | |||
932 | /** |
||
933 | * Validate a string. |
||
934 | * |
||
935 | * @param mixed $value The value to validate. |
||
936 | * @param ValidationField $field The validation results to add. |
||
937 | * @return string|Invalid Returns the valid string or **null** if validation fails. |
||
938 | */ |
||
939 | 55 | protected function validateString($value, ValidationField $field) { |
|
1028 | |||
1029 | /** |
||
1030 | * Validate a unix timestamp. |
||
1031 | * |
||
1032 | * @param mixed $value The value to validate. |
||
1033 | * @param ValidationField $field The field being validated. |
||
1034 | * @return int|Invalid Returns a valid timestamp or invalid if the value doesn't validate. |
||
1035 | */ |
||
1036 | 8 | protected function validateTimestamp($value, ValidationField $field) { |
|
1047 | |||
1048 | /** |
||
1049 | * Validate a null value. |
||
1050 | * |
||
1051 | * @param mixed $value The value to validate. |
||
1052 | * @param ValidationField $field The error collector for the field. |
||
1053 | * @return null|Invalid Returns **null** or invalid. |
||
1054 | */ |
||
1055 | protected function validateNull($value, ValidationField $field) { |
||
1062 | |||
1063 | /** |
||
1064 | * Validate a value against an enum. |
||
1065 | * |
||
1066 | * @param mixed $value The value to test. |
||
1067 | * @param ValidationField $field The validation object for adding errors. |
||
1068 | * @return mixed|Invalid Returns the value if it is one of the enumerated values or invalid otherwise. |
||
1069 | */ |
||
1070 | 118 | protected function validateEnum($value, ValidationField $field) { |
|
1089 | |||
1090 | /** |
||
1091 | * Call all of the validators attached to a field. |
||
1092 | * |
||
1093 | * @param mixed $value The field value being validated. |
||
1094 | * @param ValidationField $field The validation object to add errors. |
||
1095 | */ |
||
1096 | 118 | protected function callValidators($value, ValidationField $field) { |
|
1116 | |||
1117 | /** |
||
1118 | * Specify data which should be serialized to JSON. |
||
1119 | * |
||
1120 | * This method specifically returns data compatible with the JSON schema format. |
||
1121 | * |
||
1122 | * @return mixed Returns data which can be serialized by **json_encode()**, which is a value of any type other than a resource. |
||
1123 | * @link http://php.net/manual/en/jsonserializable.jsonserialize.php |
||
1124 | * @link http://json-schema.org/ |
||
1125 | */ |
||
1126 | public function jsonSerialize() { |
||
1161 | |||
1162 | /** |
||
1163 | * Look up a type based on its alias. |
||
1164 | * |
||
1165 | * @param string $alias The type alias or type name to lookup. |
||
1166 | * @return mixed |
||
1167 | */ |
||
1168 | 143 | protected function getType($alias) { |
|
1179 | |||
1180 | /** |
||
1181 | * Get the class that's used to contain validation information. |
||
1182 | * |
||
1183 | * @return Validation|string Returns the validation class. |
||
1184 | */ |
||
1185 | 120 | public function getValidationClass() { |
|
1188 | |||
1189 | /** |
||
1190 | * Set the class that's used to contain validation information. |
||
1191 | * |
||
1192 | * @param Validation|string $class Either the name of a class or a class that will be cloned. |
||
1193 | * @return $this |
||
1194 | */ |
||
1195 | 1 | public function setValidationClass($class) { |
|
1203 | |||
1204 | /** |
||
1205 | * Create a new validation instance. |
||
1206 | * |
||
1207 | * @return Validation Returns a validation object. |
||
1208 | */ |
||
1209 | 120 | protected function createValidation() { |
|
1219 | |||
1220 | /** |
||
1221 | * Check whether or not a value is an array or accessible like an array. |
||
1222 | * |
||
1223 | * @param mixed $value The value to check. |
||
1224 | * @return bool Returns **true** if the value can be used like an array or **false** otherwise. |
||
1225 | */ |
||
1226 | 80 | private function isArray($value) { |
|
1229 | |||
1230 | /** |
||
1231 | * Cast a value to an array. |
||
1232 | * |
||
1233 | * @param \Traversable $value The value to convert. |
||
1234 | * @return array Returns an array. |
||
1235 | */ |
||
1236 | private function toArray(\Traversable $value) { |
||
1242 | |||
1243 | /** |
||
1244 | * Return a sparse version of this schema. |
||
1245 | * |
||
1246 | * A sparse schema has no required properties. |
||
1247 | * |
||
1248 | * @return Schema Returns a new sparse schema. |
||
1249 | */ |
||
1250 | 2 | public function withSparse() { |
|
1254 | |||
1255 | /** |
||
1256 | * The internal implementation of `Schema::withSparse()`. |
||
1257 | * |
||
1258 | * @param array|Schema $schema The schema to make sparse. |
||
1259 | * @param \SplObjectStorage $schemas Collected sparse schemas that have already been made. |
||
1260 | * @return mixed |
||
1261 | */ |
||
1262 | 2 | private function withSparseInternal($schema, \SplObjectStorage $schemas) { |
|
1290 | } |
||
1291 |
If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration: