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 | 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 filter data in the schema. |
||
50 | */ |
||
51 | private $filters = []; |
||
52 | |||
53 | /** |
||
54 | * @var array An array of callbacks that will custom validate the schema. |
||
55 | */ |
||
56 | private $validators = []; |
||
57 | |||
58 | /** |
||
59 | * @var string|Validation The name of the class or an instance that will be cloned. |
||
60 | */ |
||
61 | private $validationClass = Validation::class; |
||
62 | |||
63 | |||
64 | /// Methods /// |
||
65 | |||
66 | /** |
||
67 | * Initialize an instance of a new {@link Schema} class. |
||
68 | * |
||
69 | * @param array $schema The array schema to validate against. |
||
70 | */ |
||
71 | 165 | public function __construct($schema = []) { |
|
74 | |||
75 | /** |
||
76 | * Grab the schema's current description. |
||
77 | * |
||
78 | * @return string |
||
79 | */ |
||
80 | 1 | public function getDescription() { |
|
83 | |||
84 | /** |
||
85 | * Set the description for the schema. |
||
86 | * |
||
87 | * @param string $description The new description. |
||
88 | * @throws \InvalidArgumentException Throws an exception when the provided description is not a string. |
||
89 | * @return Schema |
||
90 | */ |
||
91 | 2 | public function setDescription($description) { |
|
100 | |||
101 | /** |
||
102 | * Get a schema field. |
||
103 | * |
||
104 | * @param string|array $path The JSON schema path of the field with parts separated by dots. |
||
105 | * @param mixed $default The value to return if the field isn't found. |
||
106 | * @return mixed Returns the field value or `$default`. |
||
107 | */ |
||
108 | 4 | public function getField($path, $default = null) { |
|
125 | |||
126 | /** |
||
127 | * Set a schema field. |
||
128 | * |
||
129 | * @param string|array $path The JSON schema path of the field with parts separated by dots. |
||
130 | * @param mixed $value The new value. |
||
131 | * @return $this |
||
132 | */ |
||
133 | 3 | public function setField($path, $value) { |
|
156 | |||
157 | /** |
||
158 | * Get the ID for the schema. |
||
159 | * |
||
160 | * @return string |
||
161 | */ |
||
162 | 2 | public function getID() { |
|
165 | |||
166 | /** |
||
167 | * Set the ID for the schema. |
||
168 | * |
||
169 | * @param string $ID The new ID. |
||
170 | * @throws \InvalidArgumentException Throws an exception when the provided ID is not a string. |
||
171 | * @return Schema |
||
172 | */ |
||
173 | 3 | public function setID($ID) { |
|
182 | |||
183 | /** |
||
184 | * Return the validation flags. |
||
185 | * |
||
186 | * @return int Returns a bitwise combination of flags. |
||
187 | */ |
||
188 | 1 | public function getFlags() { |
|
191 | |||
192 | /** |
||
193 | * Set the validation flags. |
||
194 | * |
||
195 | * @param int $flags One or more of the **Schema::FLAG_*** constants. |
||
196 | * @return Schema Returns the current instance for fluent calls. |
||
197 | */ |
||
198 | 8 | public function setFlags($flags) { |
|
206 | |||
207 | /** |
||
208 | * Whether or not the schema has a flag (or combination of flags). |
||
209 | * |
||
210 | * @param int $flag One or more of the **Schema::VALIDATE_*** constants. |
||
211 | * @return bool Returns **true** if all of the flags are set or **false** otherwise. |
||
212 | */ |
||
213 | 18 | public function hasFlag($flag) { |
|
216 | |||
217 | /** |
||
218 | * Set a flag. |
||
219 | * |
||
220 | * @param int $flag One or more of the **Schema::VALIDATE_*** constants. |
||
221 | * @param bool $value Either true or false. |
||
222 | * @return $this |
||
223 | */ |
||
224 | 1 | public function setFlag($flag, $value) { |
|
232 | |||
233 | /** |
||
234 | * Merge a schema with this one. |
||
235 | * |
||
236 | * @param Schema $schema A scheme instance. Its parameters will be merged into the current instance. |
||
237 | * @return $this |
||
238 | */ |
||
239 | 3 | public function merge(Schema $schema) { |
|
243 | |||
244 | /** |
||
245 | * Add another schema to this one. |
||
246 | * |
||
247 | * Adding schemas together is analogous to array addition. When you add a schema it will only add missing information. |
||
248 | * |
||
249 | * @param Schema $schema The schema to add. |
||
250 | * @param bool $addProperties Whether to add properties that don't exist in this schema. |
||
251 | * @return $this |
||
252 | */ |
||
253 | 3 | public function add(Schema $schema, $addProperties = false) { |
|
257 | |||
258 | /** |
||
259 | * The internal implementation of schema merging. |
||
260 | * |
||
261 | * @param array &$target The target of the merge. |
||
262 | * @param array $source The source of the merge. |
||
263 | * @param bool $overwrite Whether or not to replace values. |
||
264 | * @param bool $addProperties Whether or not to add object properties to the target. |
||
265 | * @return array |
||
266 | */ |
||
267 | 6 | private function mergeInternal(array &$target, array $source, $overwrite = true, $addProperties = true) { |
|
319 | |||
320 | // public function overlay(Schema $schema ) |
||
321 | |||
322 | /** |
||
323 | * Returns the internal schema array. |
||
324 | * |
||
325 | * @return array |
||
326 | * @see Schema::jsonSerialize() |
||
327 | */ |
||
328 | 15 | public function getSchemaArray() { |
|
331 | |||
332 | /** |
||
333 | * Parse a short schema and return the associated schema. |
||
334 | * |
||
335 | * @param array $arr The schema array. |
||
336 | * @param mixed ...$args Constructor arguments for the schema instance. |
||
337 | * @return static Returns a new schema. |
||
338 | */ |
||
339 | 160 | public static function parse(array $arr, ...$args) { |
|
344 | |||
345 | /** |
||
346 | * Parse a schema in short form into a full schema array. |
||
347 | * |
||
348 | * @param array $arr The array to parse into a schema. |
||
349 | * @return array The full schema array. |
||
350 | * @throws \InvalidArgumentException Throws an exception when an item in the schema is invalid. |
||
351 | */ |
||
352 | 160 | protected function parseInternal(array $arr) { |
|
384 | |||
385 | /** |
||
386 | * Parse a schema node. |
||
387 | * |
||
388 | * @param array $node The node to parse. |
||
389 | * @param mixed $value Additional information from the node. |
||
390 | * @return array Returns a JSON schema compatible node. |
||
391 | */ |
||
392 | 154 | private function parseNode($node, $value = null) { |
|
442 | |||
443 | /** |
||
444 | * Parse the schema for an object's properties. |
||
445 | * |
||
446 | * @param array $arr An object property schema. |
||
447 | * @return array Returns a schema array suitable to be placed in the **properties** key of a schema. |
||
448 | */ |
||
449 | 99 | private function parseProperties(array $arr) { |
|
475 | |||
476 | /** |
||
477 | * Parse a short parameter string into a full array parameter. |
||
478 | * |
||
479 | * @param string $key The short parameter string to parse. |
||
480 | * @param array $value An array of other information that might help resolve ambiguity. |
||
481 | * @return array Returns an array in the form `[string name, array param, bool required]`. |
||
482 | * @throws \InvalidArgumentException Throws an exception if the short param is not in the correct format. |
||
483 | */ |
||
484 | 154 | public function parseShortParam($key, $value = []) { |
|
542 | |||
543 | /** |
||
544 | * Add a custom filter to change data before validation. |
||
545 | * |
||
546 | * @param string $fieldname The name of the field to filter, if any. |
||
547 | * |
||
548 | * If you are adding a filter to a deeply nested field then separate the path with dots. |
||
549 | * @param callable $callback The callback to filter the field. |
||
550 | * @return $this |
||
551 | */ |
||
552 | 1 | public function addFilter($fieldname, callable $callback) { |
|
556 | |||
557 | /** |
||
558 | * Add a custom validator to to validate the schema. |
||
559 | * |
||
560 | * @param string $fieldname The name of the field to validate, if any. |
||
561 | * |
||
562 | * If you are adding a validator to a deeply nested field then separate the path with dots. |
||
563 | * @param callable $callback The callback to validate with. |
||
564 | * @return Schema Returns `$this` for fluent calls. |
||
565 | */ |
||
566 | 2 | public function addValidator($fieldname, callable $callback) { |
|
570 | |||
571 | /** |
||
572 | * Require one of a given set of fields in the schema. |
||
573 | * |
||
574 | * @param array $required The field names to require. |
||
575 | * @param string $fieldname The name of the field to attach to. |
||
576 | * @param int $count The count of required items. |
||
577 | * @return Schema Returns `$this` for fluent calls. |
||
578 | */ |
||
579 | 1 | public function requireOneOf(array $required, $fieldname = '', $count = 1) { |
|
628 | |||
629 | /** |
||
630 | * Validate data against the schema. |
||
631 | * |
||
632 | * @param mixed $data The data to validate. |
||
633 | * @param bool $sparse Whether or not this is a sparse validation. |
||
634 | * @return mixed Returns a cleaned version of the data. |
||
635 | * @throws ValidationException Throws an exception when the data does not validate against the schema. |
||
636 | */ |
||
637 | 130 | public function validate($data, $sparse = false) { |
|
653 | |||
654 | /** |
||
655 | * Validate data against the schema and return the result. |
||
656 | * |
||
657 | * @param mixed $data The data to validate. |
||
658 | * @param bool $sparse Whether or not to do a sparse validation. |
||
659 | * @return bool Returns true if the data is valid. False otherwise. |
||
660 | */ |
||
661 | 33 | public function isValid($data, $sparse = false) { |
|
669 | |||
670 | /** |
||
671 | * Validate a field. |
||
672 | * |
||
673 | * @param mixed $value The value to validate. |
||
674 | * @param ValidationField $field A validation object to add errors to. |
||
675 | * @param bool $sparse Whether or not this is a sparse validation. |
||
676 | * @return mixed|Invalid Returns a clean version of the value with all extra fields stripped out or invalid if the value |
||
677 | * is completely invalid. |
||
678 | */ |
||
679 | 130 | protected function validateField($value, ValidationField $field, $sparse = false) { |
|
738 | |||
739 | /** |
||
740 | * Validate an array. |
||
741 | * |
||
742 | * @param mixed $value The value to validate. |
||
743 | * @param ValidationField $field The validation results to add. |
||
744 | * @param bool $sparse Whether or not this is a sparse validation. |
||
745 | * @return array|Invalid Returns an array or invalid if validation fails. |
||
746 | */ |
||
747 | 17 | protected function validateArray($value, ValidationField $field, $sparse = false) { |
|
779 | |||
780 | /** |
||
781 | * Validate a boolean value. |
||
782 | * |
||
783 | * @param mixed $value The value to validate. |
||
784 | * @param ValidationField $field The validation results to add. |
||
785 | * @return bool|Invalid Returns the cleaned value or invalid if validation fails. |
||
786 | */ |
||
787 | 21 | protected function validateBoolean($value, ValidationField $field) { |
|
795 | |||
796 | /** |
||
797 | * Validate a date time. |
||
798 | * |
||
799 | * @param mixed $value The value to validate. |
||
800 | * @param ValidationField $field The validation results to add. |
||
801 | * @return \DateTimeInterface|Invalid Returns the cleaned value or **null** if it isn't valid. |
||
802 | */ |
||
803 | 12 | protected function validateDatetime($value, ValidationField $field) { |
|
804 | 12 | if ($value instanceof \DateTimeInterface) { |
|
805 | // do nothing, we're good |
||
806 | 12 | } elseif (is_string($value) && $value !== '' && !is_numeric($value)) { |
|
807 | try { |
||
808 | 6 | $dt = new \DateTimeImmutable($value); |
|
809 | 5 | if ($dt) { |
|
810 | 5 | $value = $dt; |
|
811 | 5 | } else { |
|
812 | $value = null; |
||
813 | } |
||
814 | 6 | } catch (\Exception $ex) { |
|
815 | 1 | $value = Invalid::value(); |
|
816 | } |
||
817 | 10 | } elseif (is_int($value) && $value > 0) { |
|
818 | 1 | $value = new \DateTimeImmutable('@'.(string)round($value)); |
|
819 | 1 | } else { |
|
820 | 3 | $value = Invalid::value(); |
|
821 | } |
||
822 | |||
823 | 12 | if (Invalid::isInvalid($value)) { |
|
824 | 4 | $field->addTypeError('datetime'); |
|
825 | 4 | } |
|
826 | 12 | return $value; |
|
827 | } |
||
828 | |||
829 | /** |
||
830 | * Validate a float. |
||
831 | * |
||
832 | * @param mixed $value The value to validate. |
||
833 | * @param ValidationField $field The validation results to add. |
||
834 | * @return float|Invalid Returns a number or **null** if validation fails. |
||
835 | */ |
||
836 | 8 | protected function validateNumber($value, ValidationField $field) { |
|
844 | |||
845 | /** |
||
846 | * Validate and integer. |
||
847 | * |
||
848 | * @param mixed $value The value to validate. |
||
849 | * @param ValidationField $field The validation results to add. |
||
850 | * @return int|Invalid Returns the cleaned value or **null** if validation fails. |
||
851 | */ |
||
852 | 28 | protected function validateInteger($value, ValidationField $field) { |
|
861 | |||
862 | /** |
||
863 | * Validate an object. |
||
864 | * |
||
865 | * @param mixed $value The value to validate. |
||
866 | * @param ValidationField $field The validation results to add. |
||
867 | * @param bool $sparse Whether or not this is a sparse validation. |
||
868 | * @return object|Invalid Returns a clean object or **null** if validation fails. |
||
869 | */ |
||
870 | 87 | protected function validateObject($value, ValidationField $field, $sparse = false) { |
|
882 | |||
883 | /** |
||
884 | * Validate data against the schema and return the result. |
||
885 | * |
||
886 | * @param array|\ArrayAccess $data The data to validate. |
||
887 | * @param ValidationField $field This argument will be filled with the validation result. |
||
888 | * @param bool $sparse Whether or not this is a sparse validation. |
||
889 | * @return array|Invalid Returns a clean array with only the appropriate properties and the data coerced to proper types. |
||
890 | * or invalid if there are no valid properties. |
||
891 | */ |
||
892 | 86 | protected function validateProperties($data, ValidationField $field, $sparse = false) { |
|
957 | |||
958 | /** |
||
959 | * Validate a string. |
||
960 | * |
||
961 | * @param mixed $value The value to validate. |
||
962 | * @param ValidationField $field The validation results to add. |
||
963 | * @return string|Invalid Returns the valid string or **null** if validation fails. |
||
964 | */ |
||
965 | 56 | protected function validateString($value, ValidationField $field) { |
|
1054 | |||
1055 | /** |
||
1056 | * Validate a unix timestamp. |
||
1057 | * |
||
1058 | * @param mixed $value The value to validate. |
||
1059 | * @param ValidationField $field The field being validated. |
||
1060 | * @return int|Invalid Returns a valid timestamp or invalid if the value doesn't validate. |
||
1061 | */ |
||
1062 | 7 | protected function validateTimestamp($value, ValidationField $field) { |
|
1073 | |||
1074 | /** |
||
1075 | * Validate a null value. |
||
1076 | * |
||
1077 | * @param mixed $value The value to validate. |
||
1078 | * @param ValidationField $field The error collector for the field. |
||
1079 | * @return null|Invalid Returns **null** or invalid. |
||
1080 | */ |
||
1081 | protected function validateNull($value, ValidationField $field) { |
||
1088 | |||
1089 | /** |
||
1090 | * Validate a value against an enum. |
||
1091 | * |
||
1092 | * @param mixed $value The value to test. |
||
1093 | * @param ValidationField $field The validation object for adding errors. |
||
1094 | * @return mixed|Invalid Returns the value if it is one of the enumerated values or invalid otherwise. |
||
1095 | */ |
||
1096 | 128 | protected function validateEnum($value, ValidationField $field) { |
|
1115 | |||
1116 | /** |
||
1117 | * Call all of the filters attached to a field. |
||
1118 | * |
||
1119 | * @param mixed $value The field value being filtered. |
||
1120 | * @param ValidationField $field The validation object. |
||
1121 | * @return mixed Returns the filtered value. If there are no filters for the field then the original value is returned. |
||
1122 | */ |
||
1123 | 130 | protected function callFilters($value, ValidationField $field) { |
|
1133 | |||
1134 | /** |
||
1135 | * Call all of the validators attached to a field. |
||
1136 | * |
||
1137 | * @param mixed $value The field value being validated. |
||
1138 | * @param ValidationField $field The validation object to add errors. |
||
1139 | */ |
||
1140 | 128 | protected function callValidators($value, ValidationField $field) { |
|
1160 | |||
1161 | /** |
||
1162 | * Specify data which should be serialized to JSON. |
||
1163 | * |
||
1164 | * This method specifically returns data compatible with the JSON schema format. |
||
1165 | * |
||
1166 | * @return mixed Returns data which can be serialized by **json_encode()**, which is a value of any type other than a resource. |
||
1167 | * @link http://php.net/manual/en/jsonserializable.jsonserialize.php |
||
1168 | * @link http://json-schema.org/ |
||
1169 | */ |
||
1170 | public function jsonSerialize() { |
||
1205 | |||
1206 | /** |
||
1207 | * Look up a type based on its alias. |
||
1208 | * |
||
1209 | * @param string $alias The type alias or type name to lookup. |
||
1210 | * @return mixed |
||
1211 | */ |
||
1212 | 150 | protected function getType($alias) { |
|
1223 | |||
1224 | /** |
||
1225 | * Get the class that's used to contain validation information. |
||
1226 | * |
||
1227 | * @return Validation|string Returns the validation class. |
||
1228 | */ |
||
1229 | 130 | public function getValidationClass() { |
|
1232 | |||
1233 | /** |
||
1234 | * Set the class that's used to contain validation information. |
||
1235 | * |
||
1236 | * @param Validation|string $class Either the name of a class or a class that will be cloned. |
||
1237 | * @return $this |
||
1238 | */ |
||
1239 | 1 | public function setValidationClass($class) { |
|
1247 | |||
1248 | /** |
||
1249 | * Create a new validation instance. |
||
1250 | * |
||
1251 | * @return Validation Returns a validation object. |
||
1252 | */ |
||
1253 | 130 | protected function createValidation() { |
|
1263 | |||
1264 | /** |
||
1265 | * Check whether or not a value is an array or accessible like an array. |
||
1266 | * |
||
1267 | * @param mixed $value The value to check. |
||
1268 | * @return bool Returns **true** if the value can be used like an array or **false** otherwise. |
||
1269 | */ |
||
1270 | 87 | private function isArray($value) { |
|
1273 | |||
1274 | /** |
||
1275 | * Cast a value to an array. |
||
1276 | * |
||
1277 | * @param \Traversable $value The value to convert. |
||
1278 | * @return array Returns an array. |
||
1279 | */ |
||
1280 | private function toArray(\Traversable $value) { |
||
1286 | |||
1287 | /** |
||
1288 | * Return a sparse version of this schema. |
||
1289 | * |
||
1290 | * A sparse schema has no required properties. |
||
1291 | * |
||
1292 | * @return Schema Returns a new sparse schema. |
||
1293 | */ |
||
1294 | 2 | public function withSparse() { |
|
1298 | |||
1299 | /** |
||
1300 | * The internal implementation of `Schema::withSparse()`. |
||
1301 | * |
||
1302 | * @param array|Schema $schema The schema to make sparse. |
||
1303 | * @param \SplObjectStorage $schemas Collected sparse schemas that have already been made. |
||
1304 | * @return mixed |
||
1305 | */ |
||
1306 | 2 | private function withSparseInternal($schema, \SplObjectStorage $schemas) { |
|
1334 | |||
1335 | /** |
||
1336 | * Filter a field's value using built in and custom filters. |
||
1337 | * |
||
1338 | * @param mixed $value The original value of the field. |
||
1339 | * @param ValidationField $field The field information for the field. |
||
1340 | * @return mixed Returns the filtered field or the original field value if there are no filters. |
||
1341 | */ |
||
1342 | 130 | private function filterField($value, ValidationField $field) { |
|
1366 | |||
1367 | /** |
||
1368 | * Whether a offset exists. |
||
1369 | * |
||
1370 | * @param mixed $offset An offset to check for. |
||
1371 | * @return boolean true on success or false on failure. |
||
1372 | * @link http://php.net/manual/en/arrayaccess.offsetexists.php |
||
1373 | */ |
||
1374 | 3 | public function offsetExists($offset) { |
|
1377 | |||
1378 | /** |
||
1379 | * Offset to retrieve. |
||
1380 | * |
||
1381 | * @param mixed $offset The offset to retrieve. |
||
1382 | * @return mixed Can return all value types. |
||
1383 | * @link http://php.net/manual/en/arrayaccess.offsetget.php |
||
1384 | */ |
||
1385 | public function offsetGet($offset) { |
||
1388 | |||
1389 | /** |
||
1390 | * Offset to set. |
||
1391 | * |
||
1392 | * @param mixed $offset The offset to assign the value to. |
||
1393 | * @param mixed $value The value to set. |
||
1394 | * @link http://php.net/manual/en/arrayaccess.offsetset.php |
||
1395 | */ |
||
1396 | public function offsetSet($offset, $value) { |
||
1399 | |||
1400 | /** |
||
1401 | * Offset to unset. |
||
1402 | * |
||
1403 | * @param mixed $offset The offset to unset. |
||
1404 | * @link http://php.net/manual/en/arrayaccess.offsetunset.php |
||
1405 | */ |
||
1406 | public function offsetUnset($offset) { |
||
1409 | } |
||
1410 |
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.