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 | 168 | 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) { |
|
| 92 | 2 | if (is_string($description)) { |
|
| 93 | 1 | $this->schema['description'] = $description; |
|
| 94 | } else { |
||
| 95 | 1 | throw new \InvalidArgumentException("The description is not a valid string.", 500); |
|
| 96 | } |
||
| 97 | |||
| 98 | 1 | return $this; |
|
| 99 | } |
||
| 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) { |
|
| 109 | 4 | if (is_string($path)) { |
|
| 110 | 4 | $path = explode('.', $path); |
|
| 111 | } |
||
| 112 | |||
| 113 | 4 | $value = $this->schema; |
|
| 114 | 4 | foreach ($path as $i => $subKey) { |
|
| 115 | 4 | if (is_array($value) && isset($value[$subKey])) { |
|
| 116 | 4 | $value = $value[$subKey]; |
|
| 117 | 1 | } elseif ($value instanceof Schema) { |
|
| 118 | 1 | return $value->getField(array_slice($path, $i), $default); |
|
| 119 | } else { |
||
| 120 | 4 | return $default; |
|
| 121 | } |
||
| 122 | } |
||
| 123 | 4 | return $value; |
|
| 124 | } |
||
| 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) { |
|
| 134 | 3 | if (is_string($path)) { |
|
| 135 | 3 | $path = explode('.', $path); |
|
| 136 | } |
||
| 137 | |||
| 138 | 3 | $selection = &$this->schema; |
|
| 139 | 3 | foreach ($path as $i => $subSelector) { |
|
| 140 | 3 | if (is_array($selection)) { |
|
| 141 | 3 | if (!isset($selection[$subSelector])) { |
|
| 142 | 3 | $selection[$subSelector] = []; |
|
| 143 | } |
||
| 144 | 1 | } elseif ($selection instanceof Schema) { |
|
| 145 | 1 | $selection->setField(array_slice($path, $i), $value); |
|
| 146 | 1 | return $this; |
|
| 147 | } else { |
||
| 148 | $selection = [$subSelector => []]; |
||
| 149 | } |
||
| 150 | 3 | $selection = &$selection[$subSelector]; |
|
| 151 | } |
||
| 152 | |||
| 153 | 3 | $selection = $value; |
|
| 154 | 3 | return $this; |
|
| 155 | } |
||
| 156 | |||
| 157 | /** |
||
| 158 | * Get the ID for the schema. |
||
| 159 | * |
||
| 160 | * @return string |
||
| 161 | */ |
||
| 162 | 3 | 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 | 1 | public function setID($id) { |
|
| 174 | 1 | if (is_string($id)) { |
|
| 175 | 1 | $this->schema['id'] = $id; |
|
| 176 | } else { |
||
| 177 | throw new \InvalidArgumentException("The ID is not a valid string.", 500); |
||
| 178 | } |
||
| 179 | |||
| 180 | 1 | return $this; |
|
| 181 | } |
||
| 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) { |
|
| 225 | 1 | if ($value) { |
|
| 226 | 1 | $this->flags = $this->flags | $flag; |
|
| 227 | } else { |
||
| 228 | 1 | $this->flags = $this->flags & ~$flag; |
|
| 229 | } |
||
| 230 | 1 | return $this; |
|
| 231 | } |
||
| 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) { |
|
| 268 | // We need to do a fix for required properties here. |
||
| 269 | 6 | if (isset($target['properties']) && !empty($source['required'])) { |
|
| 270 | 4 | $required = isset($target['required']) ? $target['required'] : []; |
|
| 271 | |||
| 272 | 4 | if (isset($source['required']) && $addProperties) { |
|
| 273 | 3 | $newProperties = array_diff(array_keys($source['properties']), array_keys($target['properties'])); |
|
| 274 | 3 | $newRequired = array_intersect($source['required'], $newProperties); |
|
|
|
|||
| 275 | |||
| 276 | 3 | $required = array_merge($required, $newRequired); |
|
| 277 | } |
||
| 278 | } |
||
| 279 | |||
| 280 | |||
| 281 | 6 | foreach ($source as $key => $val) { |
|
| 282 | 6 | if (is_array($val) && array_key_exists($key, $target) && is_array($target[$key])) { |
|
| 283 | 6 | if ($key === 'properties' && !$addProperties) { |
|
| 284 | // We just want to merge the properties that exist in the destination. |
||
| 285 | 1 | foreach ($val as $name => $prop) { |
|
| 286 | 1 | if (isset($target[$key][$name])) { |
|
| 287 | 1 | $this->mergeInternal($target[$key][$name], $prop, $overwrite, $addProperties); |
|
| 288 | } |
||
| 289 | } |
||
| 290 | 6 | } elseif (isset($val[0]) || isset($target[$key][0])) { |
|
| 291 | 4 | if ($overwrite) { |
|
| 292 | // This is a numeric array, so just do a merge. |
||
| 293 | 2 | $merged = array_merge($target[$key], $val); |
|
| 294 | 2 | if (is_string($merged[0])) { |
|
| 295 | 2 | $merged = array_keys(array_flip($merged)); |
|
| 296 | } |
||
| 297 | 4 | $target[$key] = $merged; |
|
| 298 | } |
||
| 299 | } else { |
||
| 300 | 6 | $target[$key] = $this->mergeInternal($target[$key], $val, $overwrite, $addProperties); |
|
| 301 | } |
||
| 302 | 6 | } elseif (!$overwrite && array_key_exists($key, $target) && !is_array($val)) { |
|
| 303 | // Do nothing, we aren't replacing. |
||
| 304 | } else { |
||
| 305 | 6 | $target[$key] = $val; |
|
| 306 | } |
||
| 307 | } |
||
| 308 | |||
| 309 | 6 | if (isset($required)) { |
|
| 310 | 4 | if (empty($required)) { |
|
| 311 | 1 | unset($target['required']); |
|
| 312 | } else { |
||
| 313 | 4 | $target['required'] = $required; |
|
| 314 | } |
||
| 315 | } |
||
| 316 | |||
| 317 | 6 | return $target; |
|
| 318 | } |
||
| 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) { |
|
| 353 | 160 | if (empty($arr)) { |
|
| 354 | // An empty schema validates to anything. |
||
| 355 | 7 | return []; |
|
| 356 | 154 | } elseif (isset($arr['type'])) { |
|
| 357 | // This is a long form schema and can be parsed as the root. |
||
| 358 | return $this->parseNode($arr); |
||
| 359 | } else { |
||
| 360 | // Check for a root schema. |
||
| 361 | 154 | $value = reset($arr); |
|
| 362 | 154 | $key = key($arr); |
|
| 363 | 154 | if (is_int($key)) { |
|
| 364 | 95 | $key = $value; |
|
| 365 | 95 | $value = null; |
|
| 366 | } |
||
| 367 | 154 | list ($name, $param) = $this->parseShortParam($key, $value); |
|
| 368 | 154 | if (empty($name)) { |
|
| 369 | 58 | return $this->parseNode($param, $value); |
|
| 370 | } |
||
| 371 | } |
||
| 372 | |||
| 373 | // If we are here then this is n object schema. |
||
| 374 | 99 | list($properties, $required) = $this->parseProperties($arr); |
|
| 375 | |||
| 376 | $result = [ |
||
| 377 | 99 | 'type' => 'object', |
|
| 378 | 99 | 'properties' => $properties, |
|
| 379 | 99 | 'required' => $required |
|
| 380 | ]; |
||
| 381 | |||
| 382 | 99 | return array_filter($result); |
|
| 383 | } |
||
| 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) { |
|
| 393 | 154 | if (is_array($value)) { |
|
| 394 | // The value describes a bit more about the schema. |
||
| 395 | 57 | switch ($node['type']) { |
|
| 396 | 57 | case 'array': |
|
| 397 | 11 | if (isset($value['items'])) { |
|
| 398 | // The value includes array schema information. |
||
| 399 | 4 | $node = array_replace($node, $value); |
|
| 400 | } else { |
||
| 401 | 7 | $node['items'] = $this->parseInternal($value); |
|
| 402 | } |
||
| 403 | 11 | break; |
|
| 404 | 47 | case 'object': |
|
| 405 | // The value is a schema of the object. |
||
| 406 | 11 | if (isset($value['properties'])) { |
|
| 407 | list($node['properties']) = $this->parseProperties($value['properties']); |
||
| 408 | } else { |
||
| 409 | 11 | list($node['properties'], $required) = $this->parseProperties($value); |
|
| 410 | 11 | if (!empty($required)) { |
|
| 411 | 11 | $node['required'] = $required; |
|
| 412 | } |
||
| 413 | } |
||
| 414 | 11 | break; |
|
| 415 | default: |
||
| 416 | 36 | $node = array_replace($node, $value); |
|
| 417 | 57 | break; |
|
| 418 | } |
||
| 419 | 116 | } elseif (is_string($value)) { |
|
| 420 | 93 | if ($node['type'] === 'array' && $arrType = $this->getType($value)) { |
|
| 421 | 5 | $node['items'] = ['type' => $arrType]; |
|
| 422 | 90 | } elseif (!empty($value)) { |
|
| 423 | 93 | $node['description'] = $value; |
|
| 424 | } |
||
| 425 | 27 | } elseif ($value === null) { |
|
| 426 | // Parse child elements. |
||
| 427 | 24 | if ($node['type'] === 'array' && isset($node['items'])) { |
|
| 428 | // The value includes array schema information. |
||
| 429 | $node['items'] = $this->parseInternal($node['items']); |
||
| 430 | 24 | } elseif ($node['type'] === 'object' && isset($node['properties'])) { |
|
| 431 | list($node['properties']) = $this->parseProperties($node['properties']); |
||
| 432 | |||
| 433 | } |
||
| 434 | } |
||
| 435 | |||
| 436 | 154 | if (is_array($node) && $node['type'] === null) { |
|
| 437 | 3 | unset($node['type']); |
|
| 438 | } |
||
| 439 | |||
| 440 | 154 | return $node; |
|
| 441 | } |
||
| 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) { |
|
| 450 | 99 | $properties = []; |
|
| 451 | 99 | $requiredProperties = []; |
|
| 452 | 99 | foreach ($arr as $key => $value) { |
|
| 453 | // Fix a schema specified as just a value. |
||
| 454 | 99 | if (is_int($key)) { |
|
| 455 | 75 | if (is_string($value)) { |
|
| 456 | 75 | $key = $value; |
|
| 457 | 75 | $value = ''; |
|
| 458 | } else { |
||
| 459 | throw new \InvalidArgumentException("Schema at position $key is not a valid parameter.", 500); |
||
| 460 | } |
||
| 461 | } |
||
| 462 | |||
| 463 | // The parameter is defined in the key. |
||
| 464 | 99 | list($name, $param, $required) = $this->parseShortParam($key, $value); |
|
| 465 | |||
| 466 | 99 | $node = $this->parseNode($param, $value); |
|
| 467 | |||
| 468 | 99 | $properties[$name] = $node; |
|
| 469 | 99 | if ($required) { |
|
| 470 | 99 | $requiredProperties[] = $name; |
|
| 471 | } |
||
| 472 | } |
||
| 473 | 99 | return array($properties, $requiredProperties); |
|
| 474 | } |
||
| 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 = []) { |
|
| 485 | // Is the parameter optional? |
||
| 486 | 154 | if (substr($key, -1) === '?') { |
|
| 487 | 67 | $required = false; |
|
| 488 | 67 | $key = substr($key, 0, -1); |
|
| 489 | } else { |
||
| 490 | 108 | $required = true; |
|
| 491 | } |
||
| 492 | |||
| 493 | // Check for a type. |
||
| 494 | 154 | $parts = explode(':', $key); |
|
| 495 | 154 | $name = $parts[0]; |
|
| 496 | 154 | $allowNull = false; |
|
| 497 | 154 | if (!empty($parts[1])) { |
|
| 498 | 150 | $types = explode('|', $parts[1]); |
|
| 499 | 150 | foreach ($types as $alias) { |
|
| 500 | 150 | $found = $this->getType($alias); |
|
| 501 | 150 | if ($found === null) { |
|
| 502 | throw new \InvalidArgumentException("Unknown type '$alias'", 500); |
||
| 503 | 150 | } elseif ($found === 'null') { |
|
| 504 | 11 | $allowNull = true; |
|
| 505 | } else { |
||
| 506 | 150 | $type = $found; |
|
| 507 | } |
||
| 508 | } |
||
| 509 | } else { |
||
| 510 | 8 | $type = null; |
|
| 511 | } |
||
| 512 | |||
| 513 | 154 | if ($value instanceof Schema) { |
|
| 514 | 3 | if ($type === 'array') { |
|
| 515 | 1 | $param = ['type' => $type, 'items' => $value]; |
|
| 516 | } else { |
||
| 517 | 3 | $param = $value; |
|
| 518 | } |
||
| 519 | 154 | } elseif (isset($value['type'])) { |
|
| 520 | 3 | $param = $value; |
|
| 521 | |||
| 522 | 3 | if (!empty($type) && $type !== $param['type']) { |
|
| 523 | 3 | throw new \InvalidArgumentException("Type mismatch between $type and {$param['type']} for field $name.", 500); |
|
| 524 | } |
||
| 525 | } else { |
||
| 526 | 151 | if (empty($type) && !empty($parts[1])) { |
|
| 527 | throw new \InvalidArgumentException("Invalid type {$parts[1]} for field $name.", 500); |
||
| 528 | } |
||
| 529 | 151 | $param = ['type' => $type]; |
|
| 530 | |||
| 531 | // Parsed required strings have a minimum length of 1. |
||
| 532 | 151 | if ($type === 'string' && !empty($name) && $required && (!isset($value['default']) || $value['default'] !== '')) { |
|
| 533 | 34 | $param['minLength'] = 1; |
|
| 534 | } |
||
| 535 | } |
||
| 536 | 154 | if ($allowNull) { |
|
| 537 | 11 | $param['allowNull'] = true; |
|
| 538 | } |
||
| 539 | |||
| 540 | 154 | return [$name, $param, $required]; |
|
| 541 | } |
||
| 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) { |
|
| 580 | 1 | $result = $this->addValidator( |
|
| 581 | 1 | $fieldname, |
|
| 582 | 1 | function ($data, ValidationField $field) use ($required, $count) { |
|
| 583 | 1 | $hasCount = 0; |
|
| 584 | 1 | $flattened = []; |
|
| 585 | |||
| 586 | 1 | foreach ($required as $name) { |
|
| 587 | 1 | $flattened = array_merge($flattened, (array)$name); |
|
| 588 | |||
| 589 | 1 | if (is_array($name)) { |
|
| 590 | // This is an array of required names. They all must match. |
||
| 591 | 1 | $hasCountInner = 0; |
|
| 592 | 1 | foreach ($name as $nameInner) { |
|
| 593 | 1 | if (isset($data[$nameInner]) && $data[$nameInner]) { |
|
| 594 | 1 | $hasCountInner++; |
|
| 595 | } else { |
||
| 596 | 1 | break; |
|
| 597 | } |
||
| 598 | } |
||
| 599 | 1 | if ($hasCountInner >= count($name)) { |
|
| 600 | 1 | $hasCount++; |
|
| 601 | } |
||
| 602 | 1 | } elseif (isset($data[$name]) && $data[$name]) { |
|
| 603 | 1 | $hasCount++; |
|
| 604 | } |
||
| 605 | |||
| 606 | 1 | if ($hasCount >= $count) { |
|
| 607 | 1 | return true; |
|
| 608 | } |
||
| 609 | } |
||
| 610 | |||
| 611 | 1 | if ($count === 1) { |
|
| 612 | 1 | $message = 'One of {required} are required.'; |
|
| 613 | } else { |
||
| 614 | $message = '{count} of {required} are required.'; |
||
| 615 | } |
||
| 616 | |||
| 617 | 1 | $field->addError('missingField', [ |
|
| 618 | 1 | 'messageCode' => $message, |
|
| 619 | 1 | 'required' => $required, |
|
| 620 | 1 | 'count' => $count |
|
| 621 | ]); |
||
| 622 | 1 | return false; |
|
| 623 | 1 | } |
|
| 624 | ); |
||
| 625 | |||
| 626 | 1 | return $result; |
|
| 627 | } |
||
| 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 | 132 | public function validate($data, $sparse = false) { |
|
| 638 | 132 | $field = new ValidationField($this->createValidation(), $this->schema, '', $sparse); |
|
| 639 | |||
| 640 | 132 | $clean = $this->validateField($data, $field, $sparse); |
|
| 641 | |||
| 642 | 129 | if (Invalid::isInvalid($clean) && $field->isValid()) { |
|
| 643 | // This really shouldn't happen, but we want to protect against seeing the invalid object. |
||
| 644 | $field->addError('invalid', ['messageCode' => '{field} is invalid.', 'status' => 422]); |
||
| 645 | } |
||
| 646 | |||
| 647 | 129 | if (!$field->getValidation()->isValid()) { |
|
| 648 | 56 | throw new ValidationException($field->getValidation()); |
|
| 649 | } |
||
| 650 | |||
| 651 | 85 | return $clean; |
|
| 652 | } |
||
| 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 | 35 | 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 | 132 | protected function validateField($value, ValidationField $field, $sparse = false) { |
|
| 680 | 132 | $result = $value = $this->filterField($value, $field); |
|
| 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 | 19 | protected function validateArray($value, ValidationField $field, $sparse = false) { |
|
| 803 | |||
| 804 | /** |
||
| 805 | * Validate a boolean value. |
||
| 806 | * |
||
| 807 | * @param mixed $value The value to validate. |
||
| 808 | * @param ValidationField $field The validation results to add. |
||
| 809 | * @return bool|Invalid Returns the cleaned value or invalid if validation fails. |
||
| 810 | */ |
||
| 811 | 21 | protected function validateBoolean($value, ValidationField $field) { |
|
| 819 | |||
| 820 | /** |
||
| 821 | * Validate a date time. |
||
| 822 | * |
||
| 823 | * @param mixed $value The value to validate. |
||
| 824 | * @param ValidationField $field The validation results to add. |
||
| 825 | * @return \DateTimeInterface|Invalid Returns the cleaned value or **null** if it isn't valid. |
||
| 826 | */ |
||
| 827 | 12 | protected function validateDatetime($value, ValidationField $field) { |
|
| 852 | |||
| 853 | /** |
||
| 854 | * Validate a float. |
||
| 855 | * |
||
| 856 | * @param mixed $value The value to validate. |
||
| 857 | * @param ValidationField $field The validation results to add. |
||
| 858 | * @return float|Invalid Returns a number or **null** if validation fails. |
||
| 859 | */ |
||
| 860 | 8 | protected function validateNumber($value, ValidationField $field) { |
|
| 868 | |||
| 869 | /** |
||
| 870 | * Validate and integer. |
||
| 871 | * |
||
| 872 | * @param mixed $value The value to validate. |
||
| 873 | * @param ValidationField $field The validation results to add. |
||
| 874 | * @return int|Invalid Returns the cleaned value or **null** if validation fails. |
||
| 875 | */ |
||
| 876 | 28 | protected function validateInteger($value, ValidationField $field) { |
|
| 885 | |||
| 886 | /** |
||
| 887 | * Validate an object. |
||
| 888 | * |
||
| 889 | * @param mixed $value The value to validate. |
||
| 890 | * @param ValidationField $field The validation results to add. |
||
| 891 | * @param bool $sparse Whether or not this is a sparse validation. |
||
| 892 | * @return object|Invalid Returns a clean object or **null** if validation fails. |
||
| 893 | */ |
||
| 894 | 87 | protected function validateObject($value, ValidationField $field, $sparse = false) { |
|
| 906 | |||
| 907 | /** |
||
| 908 | * Validate data against the schema and return the result. |
||
| 909 | * |
||
| 910 | * @param array|\ArrayAccess $data The data to validate. |
||
| 911 | * @param ValidationField $field This argument will be filled with the validation result. |
||
| 912 | * @param bool $sparse Whether or not this is a sparse validation. |
||
| 913 | * @return array|Invalid Returns a clean array with only the appropriate properties and the data coerced to proper types. |
||
| 914 | * or invalid if there are no valid properties. |
||
| 915 | */ |
||
| 916 | 86 | protected function validateProperties($data, ValidationField $field, $sparse = false) { |
|
| 981 | |||
| 982 | /** |
||
| 983 | * Validate a string. |
||
| 984 | * |
||
| 985 | * @param mixed $value The value to validate. |
||
| 986 | * @param ValidationField $field The validation results to add. |
||
| 987 | * @return string|Invalid Returns the valid string or **null** if validation fails. |
||
| 988 | */ |
||
| 989 | 56 | protected function validateString($value, ValidationField $field) { |
|
| 1078 | |||
| 1079 | /** |
||
| 1080 | * Validate a unix timestamp. |
||
| 1081 | * |
||
| 1082 | * @param mixed $value The value to validate. |
||
| 1083 | * @param ValidationField $field The field being validated. |
||
| 1084 | * @return int|Invalid Returns a valid timestamp or invalid if the value doesn't validate. |
||
| 1085 | */ |
||
| 1086 | 7 | protected function validateTimestamp($value, ValidationField $field) { |
|
| 1097 | |||
| 1098 | /** |
||
| 1099 | * Validate a null value. |
||
| 1100 | * |
||
| 1101 | * @param mixed $value The value to validate. |
||
| 1102 | * @param ValidationField $field The error collector for the field. |
||
| 1103 | * @return null|Invalid Returns **null** or invalid. |
||
| 1104 | */ |
||
| 1105 | protected function validateNull($value, ValidationField $field) { |
||
| 1112 | |||
| 1113 | /** |
||
| 1114 | * Validate a value against an enum. |
||
| 1115 | * |
||
| 1116 | * @param mixed $value The value to test. |
||
| 1117 | * @param ValidationField $field The validation object for adding errors. |
||
| 1118 | * @return mixed|Invalid Returns the value if it is one of the enumerated values or invalid otherwise. |
||
| 1119 | */ |
||
| 1120 | 129 | protected function validateEnum($value, ValidationField $field) { |
|
| 1139 | |||
| 1140 | /** |
||
| 1141 | * Call all of the filters attached to a field. |
||
| 1142 | * |
||
| 1143 | * @param mixed $value The field value being filtered. |
||
| 1144 | * @param ValidationField $field The validation object. |
||
| 1145 | * @return mixed Returns the filtered value. If there are no filters for the field then the original value is returned. |
||
| 1146 | */ |
||
| 1147 | 132 | protected function callFilters($value, ValidationField $field) { |
|
| 1157 | |||
| 1158 | /** |
||
| 1159 | * Call all of the validators attached to a field. |
||
| 1160 | * |
||
| 1161 | * @param mixed $value The field value being validated. |
||
| 1162 | * @param ValidationField $field The validation object to add errors. |
||
| 1163 | */ |
||
| 1164 | 129 | protected function callValidators($value, ValidationField $field) { |
|
| 1184 | |||
| 1185 | /** |
||
| 1186 | * Specify data which should be serialized to JSON. |
||
| 1187 | * |
||
| 1188 | * This method specifically returns data compatible with the JSON schema format. |
||
| 1189 | * |
||
| 1190 | * @return mixed Returns data which can be serialized by **json_encode()**, which is a value of any type other than a resource. |
||
| 1191 | * @link http://php.net/manual/en/jsonserializable.jsonserialize.php |
||
| 1192 | * @link http://json-schema.org/ |
||
| 1193 | */ |
||
| 1194 | public function jsonSerialize() { |
||
| 1229 | |||
| 1230 | /** |
||
| 1231 | * Look up a type based on its alias. |
||
| 1232 | * |
||
| 1233 | * @param string $alias The type alias or type name to lookup. |
||
| 1234 | * @return mixed |
||
| 1235 | */ |
||
| 1236 | 150 | protected function getType($alias) { |
|
| 1247 | |||
| 1248 | /** |
||
| 1249 | * Get the class that's used to contain validation information. |
||
| 1250 | * |
||
| 1251 | * @return Validation|string Returns the validation class. |
||
| 1252 | */ |
||
| 1253 | 132 | public function getValidationClass() { |
|
| 1256 | |||
| 1257 | /** |
||
| 1258 | * Set the class that's used to contain validation information. |
||
| 1259 | * |
||
| 1260 | * @param Validation|string $class Either the name of a class or a class that will be cloned. |
||
| 1261 | * @return $this |
||
| 1262 | */ |
||
| 1263 | 1 | public function setValidationClass($class) { |
|
| 1271 | |||
| 1272 | /** |
||
| 1273 | * Create a new validation instance. |
||
| 1274 | * |
||
| 1275 | * @return Validation Returns a validation object. |
||
| 1276 | */ |
||
| 1277 | 132 | protected function createValidation() { |
|
| 1287 | |||
| 1288 | /** |
||
| 1289 | * Check whether or not a value is an array or accessible like an array. |
||
| 1290 | * |
||
| 1291 | * @param mixed $value The value to check. |
||
| 1292 | * @return bool Returns **true** if the value can be used like an array or **false** otherwise. |
||
| 1293 | */ |
||
| 1294 | 87 | private function isArray($value) { |
|
| 1297 | |||
| 1298 | /** |
||
| 1299 | * Cast a value to an array. |
||
| 1300 | * |
||
| 1301 | * @param \Traversable $value The value to convert. |
||
| 1302 | * @return array Returns an array. |
||
| 1303 | */ |
||
| 1304 | private function toArray(\Traversable $value) { |
||
| 1310 | |||
| 1311 | /** |
||
| 1312 | * Return a sparse version of this schema. |
||
| 1313 | * |
||
| 1314 | * A sparse schema has no required properties. |
||
| 1315 | * |
||
| 1316 | * @return Schema Returns a new sparse schema. |
||
| 1317 | */ |
||
| 1318 | 2 | public function withSparse() { |
|
| 1322 | |||
| 1323 | /** |
||
| 1324 | * The internal implementation of `Schema::withSparse()`. |
||
| 1325 | * |
||
| 1326 | * @param array|Schema $schema The schema to make sparse. |
||
| 1327 | * @param \SplObjectStorage $schemas Collected sparse schemas that have already been made. |
||
| 1328 | * @return mixed |
||
| 1329 | */ |
||
| 1330 | 2 | private function withSparseInternal($schema, \SplObjectStorage $schemas) { |
|
| 1358 | |||
| 1359 | /** |
||
| 1360 | * Filter a field's value using built in and custom filters. |
||
| 1361 | * |
||
| 1362 | * @param mixed $value The original value of the field. |
||
| 1363 | * @param ValidationField $field The field information for the field. |
||
| 1364 | * @return mixed Returns the filtered field or the original field value if there are no filters. |
||
| 1365 | */ |
||
| 1366 | 132 | private function filterField($value, ValidationField $field) { |
|
| 1390 | |||
| 1391 | /** |
||
| 1392 | * Whether a offset exists. |
||
| 1393 | * |
||
| 1394 | * @param mixed $offset An offset to check for. |
||
| 1395 | * @return boolean true on success or false on failure. |
||
| 1396 | * @link http://php.net/manual/en/arrayaccess.offsetexists.php |
||
| 1397 | */ |
||
| 1398 | 3 | public function offsetExists($offset) { |
|
| 1401 | |||
| 1402 | /** |
||
| 1403 | * Offset to retrieve. |
||
| 1404 | * |
||
| 1405 | * @param mixed $offset The offset to retrieve. |
||
| 1406 | * @return mixed Can return all value types. |
||
| 1407 | * @link http://php.net/manual/en/arrayaccess.offsetget.php |
||
| 1408 | */ |
||
| 1409 | public function offsetGet($offset) { |
||
| 1412 | |||
| 1413 | /** |
||
| 1414 | * Offset to set. |
||
| 1415 | * |
||
| 1416 | * @param mixed $offset The offset to assign the value to. |
||
| 1417 | * @param mixed $value The value to set. |
||
| 1418 | * @link http://php.net/manual/en/arrayaccess.offsetset.php |
||
| 1419 | */ |
||
| 1420 | public function offsetSet($offset, $value) { |
||
| 1423 | |||
| 1424 | /** |
||
| 1425 | * Offset to unset. |
||
| 1426 | * |
||
| 1427 | * @param mixed $offset The offset to unset. |
||
| 1428 | * @link http://php.net/manual/en/arrayaccess.offsetunset.php |
||
| 1429 | */ |
||
| 1430 | public function offsetUnset($offset) { |
||
| 1433 | } |
||
| 1434 |
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.