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 | 203 | public function __construct($schema = []) { |
|
| 77 | 203 | $this->schema = $schema; |
|
| 78 | 203 | } |
|
| 79 | |||
| 80 | /** |
||
| 81 | * Grab the schema's current description. |
||
| 82 | * |
||
| 83 | * @return string |
||
| 84 | */ |
||
| 85 | 1 | public function getDescription() { |
|
| 86 | 1 | return isset($this->schema['description']) ? $this->schema['description'] : ''; |
|
| 87 | } |
||
| 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) { |
|
| 97 | 2 | if (is_string($description)) { |
|
| 98 | 1 | $this->schema['description'] = $description; |
|
| 99 | } else { |
||
| 100 | 1 | throw new \InvalidArgumentException("The description is not a valid string.", 500); |
|
| 101 | } |
||
| 102 | |||
| 103 | 1 | return $this; |
|
| 104 | } |
||
| 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) { |
|
| 114 | 5 | if (is_string($path)) { |
|
| 115 | 5 | $path = explode('.', $path); |
|
| 116 | } |
||
| 117 | |||
| 118 | 5 | $value = $this->schema; |
|
| 119 | 5 | foreach ($path as $i => $subKey) { |
|
| 120 | 5 | if (is_array($value) && isset($value[$subKey])) { |
|
| 121 | 5 | $value = $value[$subKey]; |
|
| 122 | 1 | } elseif ($value instanceof Schema) { |
|
| 123 | 1 | return $value->getField(array_slice($path, $i), $default); |
|
| 124 | } else { |
||
| 125 | 5 | return $default; |
|
| 126 | } |
||
| 127 | } |
||
| 128 | 5 | return $value; |
|
| 129 | } |
||
| 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) { |
|
| 139 | 3 | if (is_string($path)) { |
|
| 140 | 3 | $path = explode('.', $path); |
|
| 141 | } |
||
| 142 | |||
| 143 | 3 | $selection = &$this->schema; |
|
| 144 | 3 | foreach ($path as $i => $subSelector) { |
|
| 145 | 3 | if (is_array($selection)) { |
|
| 146 | 3 | if (!isset($selection[$subSelector])) { |
|
| 147 | 3 | $selection[$subSelector] = []; |
|
| 148 | } |
||
| 149 | 1 | } elseif ($selection instanceof Schema) { |
|
| 150 | 1 | $selection->setField(array_slice($path, $i), $value); |
|
| 151 | 1 | return $this; |
|
| 152 | } else { |
||
| 153 | $selection = [$subSelector => []]; |
||
| 154 | } |
||
| 155 | 3 | $selection = &$selection[$subSelector]; |
|
| 156 | } |
||
| 157 | |||
| 158 | 3 | $selection = $value; |
|
| 159 | 3 | return $this; |
|
| 160 | } |
||
| 161 | |||
| 162 | /** |
||
| 163 | * Get the ID for the schema. |
||
| 164 | * |
||
| 165 | * @return string |
||
| 166 | */ |
||
| 167 | 3 | public function getID() { |
|
| 168 | 3 | return isset($this->schema['id']) ? $this->schema['id'] : ''; |
|
| 169 | } |
||
| 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) { |
|
| 179 | 1 | if (is_string($id)) { |
|
| 180 | 1 | $this->schema['id'] = $id; |
|
| 181 | } else { |
||
| 182 | throw new \InvalidArgumentException("The ID is not a valid string.", 500); |
||
| 183 | } |
||
| 184 | |||
| 185 | 1 | return $this; |
|
| 186 | } |
||
| 187 | |||
| 188 | /** |
||
| 189 | * Return the validation flags. |
||
| 190 | * |
||
| 191 | * @return int Returns a bitwise combination of flags. |
||
| 192 | */ |
||
| 193 | 1 | public function getFlags() { |
|
| 194 | 1 | return $this->flags; |
|
| 195 | } |
||
| 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) { |
|
| 204 | 8 | if (!is_int($flags)) { |
|
| 205 | 1 | throw new \InvalidArgumentException('Invalid flags.', 500); |
|
| 206 | } |
||
| 207 | 7 | $this->flags = $flags; |
|
| 208 | |||
| 209 | 7 | return $this; |
|
| 210 | } |
||
| 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 | 18 | public function hasFlag($flag) { |
|
| 219 | 18 | return ($this->flags & $flag) === $flag; |
|
| 220 | } |
||
| 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) { |
|
| 230 | 1 | if ($value) { |
|
| 231 | 1 | $this->flags = $this->flags | $flag; |
|
| 232 | } else { |
||
| 233 | 1 | $this->flags = $this->flags & ~$flag; |
|
| 234 | } |
||
| 235 | 1 | return $this; |
|
| 236 | } |
||
| 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) { |
|
| 245 | 3 | $this->mergeInternal($this->schema, $schema->getSchemaArray(), true, true); |
|
| 246 | 3 | return $this; |
|
| 247 | } |
||
| 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) { |
|
| 259 | 3 | $this->mergeInternal($this->schema, $schema->getSchemaArray(), false, $addProperties); |
|
| 260 | 3 | return $this; |
|
| 261 | } |
||
| 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) { |
|
| 273 | // We need to do a fix for required properties here. |
||
| 274 | 6 | if (isset($target['properties']) && !empty($source['required'])) { |
|
| 275 | 4 | $required = isset($target['required']) ? $target['required'] : []; |
|
| 276 | |||
| 277 | 4 | if (isset($source['required']) && $addProperties) { |
|
| 278 | 3 | $newProperties = array_diff(array_keys($source['properties']), array_keys($target['properties'])); |
|
| 279 | 3 | $newRequired = array_intersect($source['required'], $newProperties); |
|
|
|
|||
| 280 | |||
| 281 | 3 | $required = array_merge($required, $newRequired); |
|
| 282 | } |
||
| 283 | } |
||
| 284 | |||
| 285 | |||
| 286 | 6 | foreach ($source as $key => $val) { |
|
| 287 | 6 | if (is_array($val) && array_key_exists($key, $target) && is_array($target[$key])) { |
|
| 288 | 6 | if ($key === 'properties' && !$addProperties) { |
|
| 289 | // We just want to merge the properties that exist in the destination. |
||
| 290 | 1 | foreach ($val as $name => $prop) { |
|
| 291 | 1 | if (isset($target[$key][$name])) { |
|
| 292 | 1 | $this->mergeInternal($target[$key][$name], $prop, $overwrite, $addProperties); |
|
| 293 | } |
||
| 294 | } |
||
| 295 | 6 | } elseif (isset($val[0]) || isset($target[$key][0])) { |
|
| 296 | 4 | if ($overwrite) { |
|
| 297 | // This is a numeric array, so just do a merge. |
||
| 298 | 2 | $merged = array_merge($target[$key], $val); |
|
| 299 | 2 | if (is_string($merged[0])) { |
|
| 300 | 2 | $merged = array_keys(array_flip($merged)); |
|
| 301 | } |
||
| 302 | 4 | $target[$key] = $merged; |
|
| 303 | } |
||
| 304 | } else { |
||
| 305 | 6 | $target[$key] = $this->mergeInternal($target[$key], $val, $overwrite, $addProperties); |
|
| 306 | } |
||
| 307 | 6 | } elseif (!$overwrite && array_key_exists($key, $target) && !is_array($val)) { |
|
| 308 | // Do nothing, we aren't replacing. |
||
| 309 | } else { |
||
| 310 | 6 | $target[$key] = $val; |
|
| 311 | } |
||
| 312 | } |
||
| 313 | |||
| 314 | 6 | if (isset($required)) { |
|
| 315 | 4 | if (empty($required)) { |
|
| 316 | 1 | unset($target['required']); |
|
| 317 | } else { |
||
| 318 | 4 | $target['required'] = $required; |
|
| 319 | } |
||
| 320 | } |
||
| 321 | |||
| 322 | 6 | return $target; |
|
| 323 | } |
||
| 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 | 15 | public function getSchemaArray() { |
|
| 334 | 15 | return $this->schema; |
|
| 335 | } |
||
| 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 | 167 | public static function parse(array $arr, ...$args) { |
|
| 345 | 167 | $schema = new static([], ...$args); |
|
| 346 | 167 | $schema->schema = $schema->parseInternal($arr); |
|
| 347 | 167 | return $schema; |
|
| 348 | } |
||
| 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 | 167 | protected function parseInternal(array $arr) { |
|
| 358 | 167 | if (empty($arr)) { |
|
| 359 | // An empty schema validates to anything. |
||
| 360 | 7 | return []; |
|
| 361 | 161 | } elseif (isset($arr['type'])) { |
|
| 362 | // This is a long form schema and can be parsed as the root. |
||
| 363 | return $this->parseNode($arr); |
||
| 364 | } else { |
||
| 365 | // Check for a root schema. |
||
| 366 | 161 | $value = reset($arr); |
|
| 367 | 161 | $key = key($arr); |
|
| 368 | 161 | if (is_int($key)) { |
|
| 369 | 101 | $key = $value; |
|
| 370 | 101 | $value = null; |
|
| 371 | } |
||
| 372 | 161 | list ($name, $param) = $this->parseShortParam($key, $value); |
|
| 373 | 161 | if (empty($name)) { |
|
| 374 | 61 | return $this->parseNode($param, $value); |
|
| 375 | } |
||
| 376 | } |
||
| 377 | |||
| 378 | // If we are here then this is n object schema. |
||
| 379 | 103 | list($properties, $required) = $this->parseProperties($arr); |
|
| 380 | |||
| 381 | $result = [ |
||
| 382 | 103 | 'type' => 'object', |
|
| 383 | 103 | 'properties' => $properties, |
|
| 384 | 103 | 'required' => $required |
|
| 385 | ]; |
||
| 386 | |||
| 387 | 103 | return array_filter($result); |
|
| 388 | } |
||
| 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 | 161 | private function parseNode($node, $value = null) { |
|
| 398 | 161 | if (is_array($value)) { |
|
| 399 | // The value describes a bit more about the schema. |
||
| 400 | 58 | switch ($node['type']) { |
|
| 401 | 58 | case 'array': |
|
| 402 | 11 | if (isset($value['items'])) { |
|
| 403 | // The value includes array schema information. |
||
| 404 | 4 | $node = array_replace($node, $value); |
|
| 405 | } else { |
||
| 406 | 7 | $node['items'] = $this->parseInternal($value); |
|
| 407 | } |
||
| 408 | 11 | break; |
|
| 409 | 48 | case 'object': |
|
| 410 | // The value is a schema of the object. |
||
| 411 | 11 | if (isset($value['properties'])) { |
|
| 412 | list($node['properties']) = $this->parseProperties($value['properties']); |
||
| 413 | } else { |
||
| 414 | 11 | list($node['properties'], $required) = $this->parseProperties($value); |
|
| 415 | 11 | if (!empty($required)) { |
|
| 416 | 11 | $node['required'] = $required; |
|
| 417 | } |
||
| 418 | } |
||
| 419 | 11 | break; |
|
| 420 | default: |
||
| 421 | 37 | $node = array_replace($node, $value); |
|
| 422 | 58 | break; |
|
| 423 | } |
||
| 424 | 122 | } elseif (is_string($value)) { |
|
| 425 | 96 | if ($node['type'] === 'array' && $arrType = $this->getType($value)) { |
|
| 426 | 5 | $node['items'] = ['type' => $arrType]; |
|
| 427 | 93 | } elseif (!empty($value)) { |
|
| 428 | 96 | $node['description'] = $value; |
|
| 429 | } |
||
| 430 | 30 | } elseif ($value === null) { |
|
| 431 | // Parse child elements. |
||
| 432 | 27 | if ($node['type'] === 'array' && isset($node['items'])) { |
|
| 433 | // The value includes array schema information. |
||
| 434 | $node['items'] = $this->parseInternal($node['items']); |
||
| 435 | 27 | } elseif ($node['type'] === 'object' && isset($node['properties'])) { |
|
| 436 | list($node['properties']) = $this->parseProperties($node['properties']); |
||
| 437 | |||
| 438 | } |
||
| 439 | } |
||
| 440 | |||
| 441 | 161 | if (is_array($node)) { |
|
| 442 | 161 | if (!empty($node['allowNull'])) { |
|
| 443 | 1 | $node['type'] = array_merge((array)$node['type'], ['null']); |
|
| 444 | } |
||
| 445 | 161 | unset($node['allowNull']); |
|
| 446 | |||
| 447 | 161 | if ($node['type'] === null || $node['type'] === []) { |
|
| 448 | 3 | unset($node['type']); |
|
| 449 | } |
||
| 450 | } |
||
| 451 | |||
| 452 | 161 | return $node; |
|
| 453 | } |
||
| 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 | 103 | private function parseProperties(array $arr) { |
|
| 462 | 103 | $properties = []; |
|
| 463 | 103 | $requiredProperties = []; |
|
| 464 | 103 | foreach ($arr as $key => $value) { |
|
| 465 | // Fix a schema specified as just a value. |
||
| 466 | 103 | if (is_int($key)) { |
|
| 467 | 78 | if (is_string($value)) { |
|
| 468 | 78 | $key = $value; |
|
| 469 | 78 | $value = ''; |
|
| 470 | } else { |
||
| 471 | throw new \InvalidArgumentException("Schema at position $key is not a valid parameter.", 500); |
||
| 472 | } |
||
| 473 | } |
||
| 474 | |||
| 475 | // The parameter is defined in the key. |
||
| 476 | 103 | list($name, $param, $required) = $this->parseShortParam($key, $value); |
|
| 477 | |||
| 478 | 103 | $node = $this->parseNode($param, $value); |
|
| 479 | |||
| 480 | 103 | $properties[$name] = $node; |
|
| 481 | 103 | if ($required) { |
|
| 482 | 103 | $requiredProperties[] = $name; |
|
| 483 | } |
||
| 484 | } |
||
| 485 | 103 | return array($properties, $requiredProperties); |
|
| 486 | } |
||
| 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 | 161 | public function parseShortParam($key, $value = []) { |
|
| 497 | // Is the parameter optional? |
||
| 498 | 161 | if (substr($key, -1) === '?') { |
|
| 499 | 67 | $required = false; |
|
| 500 | 67 | $key = substr($key, 0, -1); |
|
| 501 | } else { |
||
| 502 | 115 | $required = true; |
|
| 503 | } |
||
| 504 | |||
| 505 | // Check for a type. |
||
| 506 | 161 | $parts = explode(':', $key); |
|
| 507 | 161 | $name = $parts[0]; |
|
| 508 | 161 | $types = []; |
|
| 509 | |||
| 510 | 161 | if (!empty($parts[1])) { |
|
| 511 | 157 | $shortTypes = explode('|', $parts[1]); |
|
| 512 | 157 | foreach ($shortTypes as $alias) { |
|
| 513 | 157 | $found = $this->getType($alias); |
|
| 514 | 157 | if ($found === null) { |
|
| 515 | throw new \InvalidArgumentException("Unknown type '$alias'", 500); |
||
| 516 | } else { |
||
| 517 | 157 | $types[] = $found; |
|
| 518 | } |
||
| 519 | } |
||
| 520 | } |
||
| 521 | |||
| 522 | 161 | if ($value instanceof Schema) { |
|
| 523 | 3 | if (count($types) === 1 && $types[0] === 'array') { |
|
| 524 | 1 | $param = ['type' => $types[0], 'items' => $value]; |
|
| 525 | } else { |
||
| 526 | 3 | $param = $value; |
|
| 527 | } |
||
| 528 | 161 | } elseif (isset($value['type'])) { |
|
| 529 | 3 | $param = $value; |
|
| 530 | |||
| 531 | 3 | if (!empty($types) && $types !== (array)$param['type']) { |
|
| 532 | $typesStr = implode('|', $types); |
||
| 533 | $paramTypesStr = implode('|', (array)$param['type']); |
||
| 534 | |||
| 535 | 3 | throw new \InvalidArgumentException("Type mismatch between $typesStr and {$paramTypesStr} for field $name.", 500); |
|
| 536 | } |
||
| 537 | } else { |
||
| 538 | 158 | if (empty($types) && !empty($parts[1])) { |
|
| 539 | throw new \InvalidArgumentException("Invalid type {$parts[1]} for field $name.", 500); |
||
| 540 | } |
||
| 541 | 158 | if (empty($types)) { |
|
| 542 | 3 | $param = ['type' => null]; |
|
| 543 | } else { |
||
| 544 | 157 | $param = ['type' => count($types) === 1 ? $types[0] : $types]; |
|
| 545 | } |
||
| 546 | |||
| 547 | // Parsed required strings have a minimum length of 1. |
||
| 548 | 158 | if (in_array('string', $types) && !empty($name) && $required && (!isset($value['default']) || $value['default'] !== '')) { |
|
| 549 | 38 | $param['minLength'] = 1; |
|
| 550 | } |
||
| 551 | } |
||
| 552 | |||
| 553 | 161 | return [$name, $param, $required]; |
|
| 554 | } |
||
| 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) { |
|
| 566 | 1 | $this->filters[$fieldname][] = $callback; |
|
| 567 | 1 | return $this; |
|
| 568 | } |
||
| 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 | 2 | public function addValidator($fieldname, callable $callback) { |
|
| 580 | 2 | $this->validators[$fieldname][] = $callback; |
|
| 581 | 2 | return $this; |
|
| 582 | } |
||
| 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 | 1 | public function requireOneOf(array $required, $fieldname = '', $count = 1) { |
|
| 593 | 1 | $result = $this->addValidator( |
|
| 594 | 1 | $fieldname, |
|
| 595 | 1 | function ($data, ValidationField $field) use ($required, $count) { |
|
| 596 | 1 | $hasCount = 0; |
|
| 597 | 1 | $flattened = []; |
|
| 598 | |||
| 599 | 1 | foreach ($required as $name) { |
|
| 600 | 1 | $flattened = array_merge($flattened, (array)$name); |
|
| 601 | |||
| 602 | 1 | if (is_array($name)) { |
|
| 603 | // This is an array of required names. They all must match. |
||
| 604 | 1 | $hasCountInner = 0; |
|
| 605 | 1 | foreach ($name as $nameInner) { |
|
| 606 | 1 | if (isset($data[$nameInner]) && $data[$nameInner]) { |
|
| 607 | 1 | $hasCountInner++; |
|
| 608 | } else { |
||
| 609 | 1 | break; |
|
| 610 | } |
||
| 611 | } |
||
| 612 | 1 | if ($hasCountInner >= count($name)) { |
|
| 613 | 1 | $hasCount++; |
|
| 614 | } |
||
| 615 | 1 | } elseif (isset($data[$name]) && $data[$name]) { |
|
| 616 | 1 | $hasCount++; |
|
| 617 | } |
||
| 618 | |||
| 619 | 1 | if ($hasCount >= $count) { |
|
| 620 | 1 | return true; |
|
| 621 | } |
||
| 622 | } |
||
| 623 | |||
| 624 | 1 | if ($count === 1) { |
|
| 625 | 1 | $message = 'One of {required} are required.'; |
|
| 626 | } else { |
||
| 627 | $message = '{count} of {required} are required.'; |
||
| 628 | } |
||
| 629 | |||
| 630 | 1 | $field->addError('missingField', [ |
|
| 631 | 1 | 'messageCode' => $message, |
|
| 632 | 1 | 'required' => $required, |
|
| 633 | 1 | 'count' => $count |
|
| 634 | ]); |
||
| 635 | 1 | return false; |
|
| 636 | 1 | } |
|
| 637 | ); |
||
| 638 | |||
| 639 | 1 | return $result; |
|
| 640 | } |
||
| 641 | |||
| 642 | /** |
||
| 643 | * Validate data against the schema. |
||
| 644 | * |
||
| 645 | * @param mixed $data The data to validate. |
||
| 646 | * @param bool $sparse Whether or not this is a sparse validation. |
||
| 647 | * @return mixed Returns a cleaned version of the data. |
||
| 648 | * @throws ValidationException Throws an exception when the data does not validate against the schema. |
||
| 649 | */ |
||
| 650 | 166 | public function validate($data, $sparse = false) { |
|
| 651 | 166 | $field = new ValidationField($this->createValidation(), $this->schema, '', $sparse); |
|
| 652 | |||
| 653 | 166 | $clean = $this->validateField($data, $field, $sparse); |
|
| 654 | |||
| 655 | 164 | if (Invalid::isInvalid($clean) && $field->isValid()) { |
|
| 656 | // This really shouldn't happen, but we want to protect against seeing the invalid object. |
||
| 657 | $field->addError('invalid', ['messageCode' => '{field} is invalid.', 'status' => 422]); |
||
| 658 | } |
||
| 659 | |||
| 660 | 164 | if (!$field->getValidation()->isValid()) { |
|
| 661 | 57 | throw new ValidationException($field->getValidation()); |
|
| 662 | } |
||
| 663 | |||
| 664 | 120 | return $clean; |
|
| 665 | } |
||
| 666 | |||
| 667 | /** |
||
| 668 | * Validate data against the schema and return the result. |
||
| 669 | * |
||
| 670 | * @param mixed $data The data to validate. |
||
| 671 | * @param bool $sparse Whether or not to do a sparse validation. |
||
| 672 | * @return bool Returns true if the data is valid. False otherwise. |
||
| 673 | */ |
||
| 674 | 35 | public function isValid($data, $sparse = false) { |
|
| 675 | try { |
||
| 676 | 35 | $this->validate($data, $sparse); |
|
| 677 | 25 | return true; |
|
| 678 | 18 | } catch (ValidationException $ex) { |
|
| 679 | 18 | return false; |
|
| 680 | } |
||
| 681 | } |
||
| 682 | |||
| 683 | /** |
||
| 684 | * Validate a field. |
||
| 685 | * |
||
| 686 | * @param mixed $value The value to validate. |
||
| 687 | * @param ValidationField $field A validation object to add errors to. |
||
| 688 | * @param bool $sparse Whether or not this is a sparse validation. |
||
| 689 | * @return mixed|Invalid Returns a clean version of the value with all extra fields stripped out or invalid if the value |
||
| 690 | * is completely invalid. |
||
| 691 | */ |
||
| 692 | 166 | protected function validateField($value, ValidationField $field, $sparse = false) { |
|
| 693 | 166 | $result = $value = $this->filterField($value, $field); |
|
| 694 | |||
| 695 | 166 | if ($field->getField() instanceof Schema) { |
|
| 696 | try { |
||
| 697 | 3 | $result = $field->getField()->validate($value, $sparse); |
|
| 698 | 1 | } catch (ValidationException $ex) { |
|
| 699 | // The validation failed, so merge the validations together. |
||
| 700 | 3 | $field->getValidation()->merge($ex->getValidation(), $field->getName()); |
|
| 701 | } |
||
| 702 | 166 | } elseif (($value === null || ($value === '' && $field->getType() !== 'string')) && $field->hasType('null')) { |
|
| 703 | 11 | $result = null; |
|
| 704 | } else { |
||
| 705 | // Validate the field's type. |
||
| 706 | 166 | $type = $field->getType(); |
|
| 707 | 166 | if (is_array($type)) { |
|
| 708 | 37 | $result = $this->validateMultipleTypes($value, $type, $field, $sparse); |
|
| 709 | } else { |
||
| 710 | 137 | $result = $this->validateSingleType($value, $type, $field, $sparse); |
|
| 711 | } |
||
| 712 | 166 | if (Invalid::isValid($result)) { |
|
| 713 | 164 | $result = $this->validateEnum($result, $field); |
|
| 714 | } |
||
| 715 | } |
||
| 716 | |||
| 717 | // Validate a custom field validator. |
||
| 718 | 166 | if (Invalid::isValid($result)) { |
|
| 719 | 164 | $this->callValidators($result, $field); |
|
| 720 | } |
||
| 721 | |||
| 722 | 166 | return $result; |
|
| 723 | } |
||
| 724 | |||
| 725 | /** |
||
| 726 | * Validate an array. |
||
| 727 | * |
||
| 728 | * @param mixed $value The value to validate. |
||
| 729 | * @param ValidationField $field The validation results to add. |
||
| 730 | * @param bool $sparse Whether or not this is a sparse validation. |
||
| 731 | * @return array|Invalid Returns an array or invalid if validation fails. |
||
| 732 | */ |
||
| 733 | 28 | protected function validateArray($value, ValidationField $field, $sparse = false) { |
|
| 734 | 28 | if ((!is_array($value) || (count($value) > 0 && !array_key_exists(0, $value))) && !$value instanceof \Traversable) { |
|
| 735 | 6 | $field->addTypeError('array'); |
|
| 736 | 6 | return Invalid::value(); |
|
| 737 | } else { |
||
| 738 | 23 | if ((null !== $minItems = $field->val('minItems')) && count($value) < $minItems) { |
|
| 739 | 1 | $field->addError( |
|
| 740 | 1 | 'minItems', |
|
| 741 | [ |
||
| 742 | 1 | 'messageCode' => '{field} must contain at least {minItems} {minItems,plural,item}.', |
|
| 743 | 1 | 'minItems' => $minItems, |
|
| 744 | 1 | 'status' => 422 |
|
| 745 | ] |
||
| 746 | ); |
||
| 747 | } |
||
| 748 | 23 | if ((null !== $maxItems = $field->val('maxItems')) && count($value) > $maxItems) { |
|
| 749 | 1 | $field->addError( |
|
| 750 | 1 | 'maxItems', |
|
| 751 | [ |
||
| 752 | 1 | 'messageCode' => '{field} must contain no more than {maxItems} {maxItems,plural,item}.', |
|
| 753 | 1 | 'maxItems' => $maxItems, |
|
| 754 | 1 | 'status' => 422 |
|
| 755 | ] |
||
| 756 | ); |
||
| 757 | } |
||
| 758 | |||
| 759 | 23 | if ($field->val('items') !== null) { |
|
| 760 | 18 | $result = []; |
|
| 761 | |||
| 762 | // Validate each of the types. |
||
| 763 | 18 | $itemValidation = new ValidationField( |
|
| 764 | 18 | $field->getValidation(), |
|
| 765 | 18 | $field->val('items'), |
|
| 766 | 18 | '', |
|
| 767 | 18 | $sparse |
|
| 768 | ); |
||
| 769 | |||
| 770 | 18 | $count = 0; |
|
| 771 | 18 | foreach ($value as $i => $item) { |
|
| 772 | 18 | $itemValidation->setName($field->getName()."[{$i}]"); |
|
| 773 | 18 | $validItem = $this->validateField($item, $itemValidation, $sparse); |
|
| 774 | 18 | if (Invalid::isValid($validItem)) { |
|
| 775 | 18 | $result[] = $validItem; |
|
| 776 | } |
||
| 777 | 18 | $count++; |
|
| 778 | } |
||
| 779 | |||
| 780 | 18 | return empty($result) && $count > 0 ? Invalid::value() : $result; |
|
| 781 | } else { |
||
| 782 | // Cast the items into a proper numeric array. |
||
| 783 | 5 | $result = is_array($value) ? array_values($value) : iterator_to_array($value); |
|
| 784 | 5 | return $result; |
|
| 785 | } |
||
| 786 | } |
||
| 787 | } |
||
| 788 | |||
| 789 | /** |
||
| 790 | * Validate a boolean value. |
||
| 791 | * |
||
| 792 | * @param mixed $value The value to validate. |
||
| 793 | * @param ValidationField $field The validation results to add. |
||
| 794 | * @return bool|Invalid Returns the cleaned value or invalid if validation fails. |
||
| 795 | */ |
||
| 796 | 29 | protected function validateBoolean($value, ValidationField $field) { |
|
| 797 | 29 | $value = $value === null ? $value : filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); |
|
| 798 | 29 | if ($value === null) { |
|
| 799 | 4 | $field->addTypeError('boolean'); |
|
| 800 | 4 | return Invalid::value(); |
|
| 801 | } |
||
| 802 | |||
| 803 | 26 | return $value; |
|
| 804 | } |
||
| 805 | |||
| 806 | /** |
||
| 807 | * Validate a date time. |
||
| 808 | * |
||
| 809 | * @param mixed $value The value to validate. |
||
| 810 | * @param ValidationField $field The validation results to add. |
||
| 811 | * @return \DateTimeInterface|Invalid Returns the cleaned value or **null** if it isn't valid. |
||
| 812 | */ |
||
| 813 | 14 | protected function validateDatetime($value, ValidationField $field) { |
|
| 814 | 14 | if ($value instanceof \DateTimeInterface) { |
|
| 815 | // do nothing, we're good |
||
| 816 | 11 | } elseif (is_string($value) && $value !== '' && !is_numeric($value)) { |
|
| 817 | try { |
||
| 818 | 7 | $dt = new \DateTimeImmutable($value); |
|
| 819 | 6 | if ($dt) { |
|
| 820 | 6 | $value = $dt; |
|
| 821 | } else { |
||
| 822 | 6 | $value = null; |
|
| 823 | } |
||
| 824 | 1 | } catch (\Exception $ex) { |
|
| 825 | 7 | $value = Invalid::value(); |
|
| 826 | } |
||
| 827 | 4 | } elseif (is_int($value) && $value > 0) { |
|
| 828 | 1 | $value = new \DateTimeImmutable('@'.(string)round($value)); |
|
| 829 | } else { |
||
| 830 | 3 | $value = Invalid::value(); |
|
| 831 | } |
||
| 832 | |||
| 833 | 14 | if (Invalid::isInvalid($value)) { |
|
| 834 | 4 | $field->addTypeError('datetime'); |
|
| 835 | } |
||
| 836 | 14 | return $value; |
|
| 837 | } |
||
| 838 | |||
| 839 | /** |
||
| 840 | * Validate a float. |
||
| 841 | * |
||
| 842 | * @param mixed $value The value to validate. |
||
| 843 | * @param ValidationField $field The validation results to add. |
||
| 844 | * @return float|Invalid Returns a number or **null** if validation fails. |
||
| 845 | */ |
||
| 846 | 13 | protected function validateNumber($value, ValidationField $field) { |
|
| 847 | 13 | $result = filter_var($value, FILTER_VALIDATE_FLOAT); |
|
| 848 | 13 | if ($result === false) { |
|
| 849 | 4 | $field->addTypeError('number'); |
|
| 850 | 4 | return Invalid::value(); |
|
| 851 | } |
||
| 852 | 9 | return $result; |
|
| 853 | } |
||
| 854 | /** |
||
| 855 | * Validate and integer. |
||
| 856 | * |
||
| 857 | * @param mixed $value The value to validate. |
||
| 858 | * @param ValidationField $field The validation results to add. |
||
| 859 | * @return int|Invalid Returns the cleaned value or **null** if validation fails. |
||
| 860 | */ |
||
| 861 | 36 | protected function validateInteger($value, ValidationField $field) { |
|
| 862 | 36 | $result = filter_var($value, FILTER_VALIDATE_INT); |
|
| 863 | |||
| 864 | 36 | if ($result === false) { |
|
| 865 | 8 | $field->addTypeError('integer'); |
|
| 866 | 8 | return Invalid::value(); |
|
| 867 | } |
||
| 868 | 31 | return $result; |
|
| 869 | } |
||
| 870 | |||
| 871 | /** |
||
| 872 | * Validate an object. |
||
| 873 | * |
||
| 874 | * @param mixed $value The value to validate. |
||
| 875 | * @param ValidationField $field The validation results to add. |
||
| 876 | * @param bool $sparse Whether or not this is a sparse validation. |
||
| 877 | * @return object|Invalid Returns a clean object or **null** if validation fails. |
||
| 878 | */ |
||
| 879 | 94 | protected function validateObject($value, ValidationField $field, $sparse = false) { |
|
| 880 | 94 | if (!$this->isArray($value) || isset($value[0])) { |
|
| 881 | 6 | $field->addTypeError('object'); |
|
| 882 | 6 | return Invalid::value(); |
|
| 883 | 94 | } elseif (is_array($field->val('properties'))) { |
|
| 884 | // Validate the data against the internal schema. |
||
| 885 | 89 | $value = $this->validateProperties($value, $field, $sparse); |
|
| 886 | 5 | } elseif (!is_array($value)) { |
|
| 887 | 3 | $value = $this->toObjectArray($value); |
|
| 888 | } |
||
| 889 | 92 | return $value; |
|
| 890 | } |
||
| 891 | |||
| 892 | /** |
||
| 893 | * Validate data against the schema and return the result. |
||
| 894 | * |
||
| 895 | * @param array|\ArrayAccess $data The data to validate. |
||
| 896 | * @param ValidationField $field This argument will be filled with the validation result. |
||
| 897 | * @param bool $sparse Whether or not this is a sparse validation. |
||
| 898 | * @return array|Invalid Returns a clean array with only the appropriate properties and the data coerced to proper types. |
||
| 899 | * or invalid if there are no valid properties. |
||
| 900 | */ |
||
| 901 | 89 | protected function validateProperties($data, ValidationField $field, $sparse = false) { |
|
| 902 | 89 | $properties = $field->val('properties', []); |
|
| 903 | 89 | $required = array_flip($field->val('required', [])); |
|
| 904 | |||
| 905 | 89 | if (is_array($data)) { |
|
| 906 | 85 | $keys = array_keys($data); |
|
| 907 | 85 | $clean = []; |
|
| 908 | } else { |
||
| 909 | 4 | $keys = array_keys(iterator_to_array($data)); |
|
| 910 | 4 | $class = get_class($data); |
|
| 911 | 4 | $clean = new $class; |
|
| 912 | |||
| 913 | 4 | if ($clean instanceof \ArrayObject) { |
|
| 914 | 3 | $clean->setFlags($data->getFlags()); |
|
| 915 | 3 | $clean->setIteratorClass($data->getIteratorClass()); |
|
| 916 | } |
||
| 917 | } |
||
| 918 | 89 | $keys = array_combine(array_map('strtolower', $keys), $keys); |
|
| 919 | |||
| 920 | 89 | $propertyField = new ValidationField($field->getValidation(), [], null, $sparse); |
|
| 921 | |||
| 922 | // Loop through the schema fields and validate each one. |
||
| 923 | 89 | foreach ($properties as $propertyName => $property) { |
|
| 924 | $propertyField |
||
| 925 | 89 | ->setField($property) |
|
| 926 | 89 | ->setName(ltrim($field->getName().".$propertyName", '.')); |
|
| 927 | |||
| 928 | 89 | $lName = strtolower($propertyName); |
|
| 929 | 89 | $isRequired = isset($required[$propertyName]); |
|
| 930 | |||
| 931 | // First check for required fields. |
||
| 932 | 89 | if (!array_key_exists($lName, $keys)) { |
|
| 933 | 23 | if ($sparse) { |
|
| 934 | // Sparse validation can leave required fields out. |
||
| 935 | 23 | } elseif ($propertyField->hasVal('default')) { |
|
| 936 | 2 | $clean[$propertyName] = $propertyField->val('default'); |
|
| 937 | 21 | } elseif ($isRequired) { |
|
| 938 | 23 | $propertyField->addError('missingField', ['messageCode' => '{field} is required.']); |
|
| 939 | } |
||
| 940 | } else { |
||
| 941 | 87 | $value = $data[$keys[$lName]]; |
|
| 942 | |||
| 943 | 87 | if (in_array($value, [null, ''], true) && !$isRequired && !$propertyField->hasType('null')) { |
|
| 944 | 13 | if ($propertyField->getType() !== 'string' || $value === null) { |
|
| 945 | 10 | continue; |
|
| 946 | } |
||
| 947 | } |
||
| 948 | |||
| 949 | 77 | $clean[$propertyName] = $this->validateField($value, $propertyField, $sparse); |
|
| 950 | } |
||
| 951 | |||
| 952 | 87 | unset($keys[$lName]); |
|
| 953 | } |
||
| 954 | |||
| 955 | // Look for extraneous properties. |
||
| 956 | 89 | if (!empty($keys)) { |
|
| 957 | 17 | if ($this->hasFlag(Schema::VALIDATE_EXTRA_PROPERTY_NOTICE)) { |
|
| 958 | 2 | $msg = sprintf("%s has unexpected field(s): %s.", $field->getName() ?: 'value', implode(', ', $keys)); |
|
| 959 | 2 | trigger_error($msg, E_USER_NOTICE); |
|
| 960 | } |
||
| 961 | |||
| 962 | 15 | if ($this->hasFlag(Schema::VALIDATE_EXTRA_PROPERTY_EXCEPTION)) { |
|
| 963 | 2 | $field->addError('invalid', [ |
|
| 964 | 2 | 'messageCode' => '{field} has {extra,plural,an unexpected field,unexpected fields}: {extra}.', |
|
| 965 | 2 | 'extra' => array_values($keys), |
|
| 966 | 2 | 'status' => 422 |
|
| 967 | ]); |
||
| 968 | } |
||
| 969 | } |
||
| 970 | |||
| 971 | 87 | return $clean; |
|
| 972 | } |
||
| 973 | |||
| 974 | /** |
||
| 975 | * Validate a string. |
||
| 976 | * |
||
| 977 | * @param mixed $value The value to validate. |
||
| 978 | * @param ValidationField $field The validation results to add. |
||
| 979 | * @return string|Invalid Returns the valid string or **null** if validation fails. |
||
| 980 | */ |
||
| 981 | 63 | protected function validateString($value, ValidationField $field) { |
|
| 982 | 63 | if (is_string($value) || is_numeric($value)) { |
|
| 983 | 61 | $value = $result = (string)$value; |
|
| 984 | } else { |
||
| 985 | 5 | $field->addTypeError('string'); |
|
| 986 | 5 | return Invalid::value(); |
|
| 987 | } |
||
| 988 | |||
| 989 | 61 | $errorCount = $field->getErrorCount(); |
|
| 990 | 61 | if (($minLength = $field->val('minLength', 0)) > 0 && mb_strlen($value) < $minLength) { |
|
| 991 | 4 | if (!empty($field->getName()) && $minLength === 1) { |
|
| 992 | 2 | $field->addError('missingField', ['messageCode' => '{field} is required.', 'status' => 422]); |
|
| 993 | } else { |
||
| 994 | 2 | $field->addError( |
|
| 995 | 2 | 'minLength', |
|
| 996 | [ |
||
| 997 | 2 | 'messageCode' => '{field} should be at least {minLength} {minLength,plural,character} long.', |
|
| 998 | 2 | 'minLength' => $minLength, |
|
| 999 | 2 | 'status' => 422 |
|
| 1000 | ] |
||
| 1001 | ); |
||
| 1002 | } |
||
| 1003 | } |
||
| 1004 | 61 | if (($maxLength = $field->val('maxLength', 0)) > 0 && mb_strlen($value) > $maxLength) { |
|
| 1005 | 1 | $field->addError( |
|
| 1006 | 1 | 'maxLength', |
|
| 1007 | [ |
||
| 1008 | 1 | 'messageCode' => '{field} is {overflow} {overflow,plural,characters} too long.', |
|
| 1009 | 1 | 'maxLength' => $maxLength, |
|
| 1010 | 1 | 'overflow' => mb_strlen($value) - $maxLength, |
|
| 1011 | 1 | 'status' => 422 |
|
| 1012 | ] |
||
| 1013 | ); |
||
| 1014 | } |
||
| 1015 | 61 | if ($pattern = $field->val('pattern')) { |
|
| 1016 | 4 | $regex = '`'.str_replace('`', preg_quote('`', '`'), $pattern).'`'; |
|
| 1017 | |||
| 1018 | 4 | if (!preg_match($regex, $value)) { |
|
| 1019 | 2 | $field->addError( |
|
| 1020 | 2 | 'invalid', |
|
| 1021 | [ |
||
| 1022 | 2 | 'messageCode' => '{field} is in the incorrect format.', |
|
| 1023 | 'status' => 422 |
||
| 1024 | ] |
||
| 1025 | ); |
||
| 1026 | } |
||
| 1027 | } |
||
| 1028 | 61 | if ($format = $field->val('format')) { |
|
| 1029 | 15 | $type = $format; |
|
| 1030 | switch ($format) { |
||
| 1031 | 15 | case 'date-time': |
|
| 1032 | 4 | $result = $this->validateDatetime($result, $field); |
|
| 1033 | 4 | if ($result instanceof \DateTimeInterface) { |
|
| 1034 | 4 | $result = $result->format(\DateTime::RFC3339); |
|
| 1035 | } |
||
| 1036 | 4 | break; |
|
| 1037 | 11 | case 'email': |
|
| 1038 | 1 | $result = filter_var($result, FILTER_VALIDATE_EMAIL); |
|
| 1039 | 1 | break; |
|
| 1040 | 10 | case 'ipv4': |
|
| 1041 | 1 | $type = 'IPv4 address'; |
|
| 1042 | 1 | $result = filter_var($result, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4); |
|
| 1043 | 1 | break; |
|
| 1044 | 9 | case 'ipv6': |
|
| 1045 | 1 | $type = 'IPv6 address'; |
|
| 1046 | 1 | $result = filter_var($result, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6); |
|
| 1047 | 1 | break; |
|
| 1048 | 8 | case 'ip': |
|
| 1049 | 1 | $type = 'IP address'; |
|
| 1050 | 1 | $result = filter_var($result, FILTER_VALIDATE_IP); |
|
| 1051 | 1 | break; |
|
| 1052 | 7 | case 'uri': |
|
| 1053 | 7 | $type = 'URI'; |
|
| 1054 | 7 | $result = filter_var($result, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED | FILTER_FLAG_SCHEME_REQUIRED); |
|
| 1055 | 7 | break; |
|
| 1056 | default: |
||
| 1057 | trigger_error("Unrecognized format '$format'.", E_USER_NOTICE); |
||
| 1058 | } |
||
| 1059 | 15 | if ($result === false) { |
|
| 1060 | 5 | $field->addTypeError($type); |
|
| 1061 | } |
||
| 1062 | } |
||
| 1063 | |||
| 1064 | 61 | if ($field->isValid()) { |
|
| 1065 | 53 | return $result; |
|
| 1066 | } else { |
||
| 1067 | 12 | return Invalid::value(); |
|
| 1068 | } |
||
| 1069 | } |
||
| 1070 | |||
| 1071 | /** |
||
| 1072 | * Validate a unix timestamp. |
||
| 1073 | * |
||
| 1074 | * @param mixed $value The value to validate. |
||
| 1075 | * @param ValidationField $field The field being validated. |
||
| 1076 | * @return int|Invalid Returns a valid timestamp or invalid if the value doesn't validate. |
||
| 1077 | */ |
||
| 1078 | 8 | protected function validateTimestamp($value, ValidationField $field) { |
|
| 1079 | 8 | if (is_numeric($value) && $value > 0) { |
|
| 1080 | 3 | $result = (int)$value; |
|
| 1081 | 5 | } elseif (is_string($value) && $ts = strtotime($value)) { |
|
| 1082 | 1 | $result = $ts; |
|
| 1083 | } else { |
||
| 1084 | 4 | $field->addTypeError('timestamp'); |
|
| 1085 | 4 | $result = Invalid::value(); |
|
| 1086 | } |
||
| 1087 | 8 | return $result; |
|
| 1088 | } |
||
| 1089 | |||
| 1090 | /** |
||
| 1091 | * Validate a null value. |
||
| 1092 | * |
||
| 1093 | * @param mixed $value The value to validate. |
||
| 1094 | * @param ValidationField $field The error collector for the field. |
||
| 1095 | * @return null|Invalid Returns **null** or invalid. |
||
| 1096 | */ |
||
| 1097 | protected function validateNull($value, ValidationField $field) { |
||
| 1098 | if ($value === null) { |
||
| 1099 | return null; |
||
| 1100 | } |
||
| 1101 | $field->addError('invalid', ['messageCode' => '{field} should be null.', 'status' => 422]); |
||
| 1102 | return Invalid::value(); |
||
| 1103 | } |
||
| 1104 | |||
| 1105 | /** |
||
| 1106 | * Validate a value against an enum. |
||
| 1107 | * |
||
| 1108 | * @param mixed $value The value to test. |
||
| 1109 | * @param ValidationField $field The validation object for adding errors. |
||
| 1110 | * @return mixed|Invalid Returns the value if it is one of the enumerated values or invalid otherwise. |
||
| 1111 | */ |
||
| 1112 | 164 | protected function validateEnum($value, ValidationField $field) { |
|
| 1113 | 164 | $enum = $field->val('enum'); |
|
| 1114 | 164 | if (empty($enum)) { |
|
| 1115 | 163 | return $value; |
|
| 1116 | } |
||
| 1117 | |||
| 1118 | 1 | if (!in_array($value, $enum, true)) { |
|
| 1119 | 1 | $field->addError( |
|
| 1120 | 1 | 'invalid', |
|
| 1121 | [ |
||
| 1122 | 1 | 'messageCode' => '{field} must be one of: {enum}.', |
|
| 1123 | 1 | 'enum' => $enum, |
|
| 1124 | 1 | 'status' => 422 |
|
| 1125 | ] |
||
| 1126 | ); |
||
| 1127 | 1 | return Invalid::value(); |
|
| 1128 | } |
||
| 1129 | 1 | return $value; |
|
| 1130 | } |
||
| 1131 | |||
| 1132 | /** |
||
| 1133 | * Call all of the filters attached to a field. |
||
| 1134 | * |
||
| 1135 | * @param mixed $value The field value being filtered. |
||
| 1136 | * @param ValidationField $field The validation object. |
||
| 1137 | * @return mixed Returns the filtered value. If there are no filters for the field then the original value is returned. |
||
| 1138 | */ |
||
| 1139 | 166 | protected function callFilters($value, ValidationField $field) { |
|
| 1140 | // Strip array references in the name except for the last one. |
||
| 1141 | 166 | $key = preg_replace(['`\[\d+\]$`', '`\[\d+\]`'], ['[]', ''], $field->getName()); |
|
| 1142 | 166 | if (!empty($this->filters[$key])) { |
|
| 1143 | 1 | foreach ($this->filters[$key] as $filter) { |
|
| 1144 | 1 | $value = call_user_func($filter, $value, $field); |
|
| 1145 | } |
||
| 1146 | } |
||
| 1147 | 166 | return $value; |
|
| 1148 | } |
||
| 1149 | |||
| 1150 | /** |
||
| 1151 | * Call all of the validators attached to a field. |
||
| 1152 | * |
||
| 1153 | * @param mixed $value The field value being validated. |
||
| 1154 | * @param ValidationField $field The validation object to add errors. |
||
| 1155 | */ |
||
| 1156 | 164 | protected function callValidators($value, ValidationField $field) { |
|
| 1157 | 164 | $valid = true; |
|
| 1158 | |||
| 1159 | // Strip array references in the name except for the last one. |
||
| 1160 | 164 | $key = preg_replace(['`\[\d+\]$`', '`\[\d+\]`'], ['[]', ''], $field->getName()); |
|
| 1161 | 164 | if (!empty($this->validators[$key])) { |
|
| 1162 | 2 | foreach ($this->validators[$key] as $validator) { |
|
| 1163 | 2 | $r = call_user_func($validator, $value, $field); |
|
| 1164 | |||
| 1165 | 2 | if ($r === false || Invalid::isInvalid($r)) { |
|
| 1166 | 2 | $valid = false; |
|
| 1167 | } |
||
| 1168 | } |
||
| 1169 | } |
||
| 1170 | |||
| 1171 | // Add an error on the field if the validator hasn't done so. |
||
| 1172 | 164 | if (!$valid && $field->isValid()) { |
|
| 1173 | $field->addError('invalid', ['messageCode' => '{field} is invalid.', 'status' => 422]); |
||
| 1174 | } |
||
| 1175 | 164 | } |
|
| 1176 | |||
| 1177 | /** |
||
| 1178 | * Specify data which should be serialized to JSON. |
||
| 1179 | * |
||
| 1180 | * This method specifically returns data compatible with the JSON schema format. |
||
| 1181 | * |
||
| 1182 | * @return mixed Returns data which can be serialized by **json_encode()**, which is a value of any type other than a resource. |
||
| 1183 | * @link http://php.net/manual/en/jsonserializable.jsonserialize.php |
||
| 1184 | * @link http://json-schema.org/ |
||
| 1185 | */ |
||
| 1186 | public function jsonSerialize() { |
||
| 1187 | 14 | $fix = function ($schema) use (&$fix) { |
|
| 1188 | 14 | if ($schema instanceof Schema) { |
|
| 1189 | 1 | return $schema->jsonSerialize(); |
|
| 1190 | } |
||
| 1191 | |||
| 1192 | 14 | if (!empty($schema['type'])) { |
|
| 1193 | // Swap datetime and timestamp to other types with formats. |
||
| 1194 | 13 | if ($schema['type'] === 'datetime') { |
|
| 1195 | 3 | $schema['type'] = 'string'; |
|
| 1196 | 3 | $schema['format'] = 'date-time'; |
|
| 1197 | 12 | } elseif ($schema['type'] === 'timestamp') { |
|
| 1198 | 3 | $schema['type'] = 'integer'; |
|
| 1199 | 3 | $schema['format'] = 'timestamp'; |
|
| 1200 | } |
||
| 1201 | } |
||
| 1202 | |||
| 1203 | 14 | if (!empty($schema['items'])) { |
|
| 1204 | 4 | $schema['items'] = $fix($schema['items']); |
|
| 1205 | } |
||
| 1206 | 14 | if (!empty($schema['properties'])) { |
|
| 1207 | 10 | $properties = []; |
|
| 1208 | 10 | foreach ($schema['properties'] as $key => $property) { |
|
| 1209 | 10 | $properties[$key] = $fix($property); |
|
| 1210 | } |
||
| 1211 | 10 | $schema['properties'] = $properties; |
|
| 1212 | } |
||
| 1213 | |||
| 1214 | 14 | return $schema; |
|
| 1215 | 14 | }; |
|
| 1216 | |||
| 1217 | 14 | $result = $fix($this->schema); |
|
| 1218 | |||
| 1219 | 14 | return $result; |
|
| 1220 | } |
||
| 1221 | |||
| 1222 | /** |
||
| 1223 | * Look up a type based on its alias. |
||
| 1224 | * |
||
| 1225 | * @param string $alias The type alias or type name to lookup. |
||
| 1226 | * @return mixed |
||
| 1227 | */ |
||
| 1228 | 157 | protected function getType($alias) { |
|
| 1229 | 157 | if (isset(self::$types[$alias])) { |
|
| 1230 | return $alias; |
||
| 1231 | } |
||
| 1232 | 157 | foreach (self::$types as $type => $aliases) { |
|
| 1233 | 157 | if (in_array($alias, $aliases, true)) { |
|
| 1234 | 157 | return $type; |
|
| 1235 | } |
||
| 1236 | } |
||
| 1237 | 9 | return null; |
|
| 1238 | } |
||
| 1239 | |||
| 1240 | /** |
||
| 1241 | * Get the class that's used to contain validation information. |
||
| 1242 | * |
||
| 1243 | * @return Validation|string Returns the validation class. |
||
| 1244 | */ |
||
| 1245 | 166 | public function getValidationClass() { |
|
| 1246 | 166 | return $this->validationClass; |
|
| 1247 | } |
||
| 1248 | |||
| 1249 | /** |
||
| 1250 | * Set the class that's used to contain validation information. |
||
| 1251 | * |
||
| 1252 | * @param Validation|string $class Either the name of a class or a class that will be cloned. |
||
| 1253 | * @return $this |
||
| 1254 | */ |
||
| 1255 | 1 | public function setValidationClass($class) { |
|
| 1256 | 1 | if (!is_a($class, Validation::class, true)) { |
|
| 1257 | throw new \InvalidArgumentException("$class must be a subclass of ".Validation::class, 500); |
||
| 1258 | } |
||
| 1259 | |||
| 1260 | 1 | $this->validationClass = $class; |
|
| 1261 | 1 | return $this; |
|
| 1262 | } |
||
| 1263 | |||
| 1264 | /** |
||
| 1265 | * Create a new validation instance. |
||
| 1266 | * |
||
| 1267 | * @return Validation Returns a validation object. |
||
| 1268 | */ |
||
| 1269 | 166 | protected function createValidation() { |
|
| 1270 | 166 | $class = $this->getValidationClass(); |
|
| 1271 | |||
| 1272 | 166 | if ($class instanceof Validation) { |
|
| 1273 | 1 | $result = clone $class; |
|
| 1274 | } else { |
||
| 1275 | 166 | $result = new $class; |
|
| 1276 | } |
||
| 1277 | 166 | return $result; |
|
| 1278 | } |
||
| 1279 | |||
| 1280 | /** |
||
| 1281 | * Check whether or not a value is an array or accessible like an array. |
||
| 1282 | * |
||
| 1283 | * @param mixed $value The value to check. |
||
| 1284 | * @return bool Returns **true** if the value can be used like an array or **false** otherwise. |
||
| 1285 | */ |
||
| 1286 | 94 | private function isArray($value) { |
|
| 1287 | 94 | return is_array($value) || ($value instanceof \ArrayAccess && $value instanceof \Traversable); |
|
| 1288 | } |
||
| 1289 | |||
| 1290 | /** |
||
| 1291 | * Cast a value to an array. |
||
| 1292 | * |
||
| 1293 | * @param \Traversable $value The value to convert. |
||
| 1294 | * @return array Returns an array. |
||
| 1295 | */ |
||
| 1296 | 3 | private function toObjectArray(\Traversable $value) { |
|
| 1297 | 3 | $class = get_class($value); |
|
| 1298 | 3 | if ($value instanceof \ArrayObject) { |
|
| 1299 | 2 | return new $class($value->getArrayCopy(), $value->getFlags(), $value->getIteratorClass()); |
|
| 1300 | 1 | } elseif ($value instanceof \ArrayAccess) { |
|
| 1301 | 1 | $r = new $class; |
|
| 1302 | 1 | foreach ($value as $k => $v) { |
|
| 1303 | 1 | $r[$k] = $v; |
|
| 1304 | } |
||
| 1305 | 1 | return $r; |
|
| 1306 | } |
||
| 1307 | return iterator_to_array($value); |
||
| 1308 | } |
||
| 1309 | |||
| 1310 | /** |
||
| 1311 | * Return a sparse version of this schema. |
||
| 1312 | * |
||
| 1313 | * A sparse schema has no required properties. |
||
| 1314 | * |
||
| 1315 | * @return Schema Returns a new sparse schema. |
||
| 1316 | */ |
||
| 1317 | 2 | public function withSparse() { |
|
| 1321 | |||
| 1322 | /** |
||
| 1323 | * The internal implementation of `Schema::withSparse()`. |
||
| 1324 | * |
||
| 1325 | * @param array|Schema $schema The schema to make sparse. |
||
| 1326 | * @param \SplObjectStorage $schemas Collected sparse schemas that have already been made. |
||
| 1327 | * @return mixed |
||
| 1328 | */ |
||
| 1329 | 2 | private function withSparseInternal($schema, \SplObjectStorage $schemas) { |
|
| 1330 | 2 | if ($schema instanceof Schema) { |
|
| 1331 | 2 | if ($schemas->contains($schema)) { |
|
| 1332 | 1 | return $schemas[$schema]; |
|
| 1333 | } else { |
||
| 1334 | 2 | $schemas[$schema] = $sparseSchema = new Schema(); |
|
| 1335 | 2 | $sparseSchema->schema = $schema->withSparseInternal($schema->schema, $schemas); |
|
| 1336 | 2 | if ($id = $sparseSchema->getID()) { |
|
| 1337 | $sparseSchema->setID($id.'Sparse'); |
||
| 1338 | } |
||
| 1339 | |||
| 1340 | 2 | return $sparseSchema; |
|
| 1341 | } |
||
| 1342 | } |
||
| 1343 | |||
| 1344 | 2 | unset($schema['required']); |
|
| 1345 | |||
| 1346 | 2 | if (isset($schema['items'])) { |
|
| 1347 | 1 | $schema['items'] = $this->withSparseInternal($schema['items'], $schemas); |
|
| 1348 | } |
||
| 1349 | 2 | if (isset($schema['properties'])) { |
|
| 1350 | 2 | foreach ($schema['properties'] as $name => &$property) { |
|
| 1351 | 2 | $property = $this->withSparseInternal($property, $schemas); |
|
| 1352 | } |
||
| 1353 | } |
||
| 1354 | |||
| 1355 | 2 | return $schema; |
|
| 1356 | } |
||
| 1357 | |||
| 1358 | /** |
||
| 1359 | * Filter a field's value using built in and custom filters. |
||
| 1360 | * |
||
| 1361 | * @param mixed $value The original value of the field. |
||
| 1362 | * @param ValidationField $field The field information for the field. |
||
| 1363 | * @return mixed Returns the filtered field or the original field value if there are no filters. |
||
| 1364 | */ |
||
| 1365 | 166 | private function filterField($value, ValidationField $field) { |
|
| 1366 | // Check for limited support for Open API style. |
||
| 1367 | 166 | if (!empty($field->val('style')) && is_string($value)) { |
|
| 1368 | 8 | $doFilter = true; |
|
| 1394 | |||
| 1395 | /** |
||
| 1396 | * Whether a offset exists. |
||
| 1397 | * |
||
| 1398 | * @param mixed $offset An offset to check for. |
||
| 1399 | * @return boolean true on success or false on failure. |
||
| 1400 | * @link http://php.net/manual/en/arrayaccess.offsetexists.php |
||
| 1401 | */ |
||
| 1402 | 3 | public function offsetExists($offset) { |
|
| 1405 | |||
| 1406 | /** |
||
| 1407 | * Offset to retrieve. |
||
| 1408 | * |
||
| 1409 | * @param mixed $offset The offset to retrieve. |
||
| 1410 | * @return mixed Can return all value types. |
||
| 1411 | * @link http://php.net/manual/en/arrayaccess.offsetget.php |
||
| 1412 | */ |
||
| 1413 | public function offsetGet($offset) { |
||
| 1416 | |||
| 1417 | /** |
||
| 1418 | * Offset to set. |
||
| 1419 | * |
||
| 1420 | * @param mixed $offset The offset to assign the value to. |
||
| 1421 | * @param mixed $value The value to set. |
||
| 1422 | * @link http://php.net/manual/en/arrayaccess.offsetset.php |
||
| 1423 | */ |
||
| 1424 | public function offsetSet($offset, $value) { |
||
| 1427 | |||
| 1428 | /** |
||
| 1429 | * Offset to unset. |
||
| 1430 | * |
||
| 1431 | * @param mixed $offset The offset to unset. |
||
| 1432 | * @link http://php.net/manual/en/arrayaccess.offsetunset.php |
||
| 1433 | */ |
||
| 1434 | public function offsetUnset($offset) { |
||
| 1437 | |||
| 1438 | /** |
||
| 1439 | * Validate a field against a single type. |
||
| 1440 | * |
||
| 1441 | * @param mixed $value The value to validate. |
||
| 1442 | * @param string $type The type to validate against. |
||
| 1443 | * @param ValidationField $field Contains field and validation information. |
||
| 1444 | * @param bool $sparse Whether or not this should be a sparse validation. |
||
| 1445 | * @return mixed Returns the valid value or `Invalid`. |
||
| 1446 | */ |
||
| 1447 | 166 | protected function validateSingleType($value, $type, ValidationField $field, $sparse) { |
|
| 1485 | |||
| 1486 | /** |
||
| 1487 | * Validate a field against multiple basic types. |
||
| 1488 | * |
||
| 1489 | * The first validation that passes will be returned. If no type can be validated against then validation will fail. |
||
| 1490 | * |
||
| 1491 | * @param mixed $value The value to validate. |
||
| 1492 | * @param string[] $types The types to validate against. |
||
| 1493 | * @param ValidationField $field Contains field and validation information. |
||
| 1494 | * @param bool $sparse Whether or not this should be a sparse validation. |
||
| 1495 | * @return mixed Returns the valid value or `Invalid`. |
||
| 1496 | */ |
||
| 1497 | 37 | private function validateMultipleTypes($value, array $types, ValidationField $field, $sparse) { |
|
| 1560 | } |
||
| 1561 |
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.