Passed
Push — master ( 76e443...4a7680 )
by Todd
37s
created

src/Schema.php (4 issues)

1
<?php
2
/**
3
 * @author Todd Burry <[email protected]>
4
 * @copyright 2009-2018 Vanilla Forums Inc.
5
 * @license MIT
6
 */
7
8
namespace Garden\Schema;
9
10
/**
11
 * A class for defining and validating data schemas.
12
 */
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 178
    public function __construct(array $schema = []) {
77 178
        $this->schema = $schema;
78 178
    }
79
80
    /**
81
     * Grab the schema's current description.
82
     *
83
     * @return string
84
     */
85 1
    public function getDescription(): string {
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
     * @return $this
94
     */
95
    public function setDescription(string $description) {
96 2
        $this->schema['description'] = $description;
97 2
        return $this;
98 1
    }
99
100 1
    /**
101
     * Get a schema field.
102
     *
103 1
     * @param string|array $path The JSON schema path of the field with parts separated by dots.
104
     * @param mixed $default The value to return if the field isn't found.
105
     * @return mixed Returns the field value or `$default`.
106
     */
107
    public function getField($path, $default = null) {
108
        if (is_string($path)) {
109
            $path = explode('.', $path);
110
        }
111
112
        $value = $this->schema;
113 5
        foreach ($path as $i => $subKey) {
114 5
            if (is_array($value) && isset($value[$subKey])) {
115 5
                $value = $value[$subKey];
116
            } elseif ($value instanceof Schema) {
117
                return $value->getField(array_slice($path, $i), $default);
118 5
            } else {
119 5
                return $default;
120 5
            }
121 5
        }
122 1
        return $value;
123 1
    }
124
125 5
    /**
126
     * Set a schema field.
127
     *
128 5
     * @param string|array $path The JSON schema path of the field with parts separated by dots.
129
     * @param mixed $value The new value.
130
     * @return $this
131
     */
132
    public function setField($path, $value) {
133
        if (is_string($path)) {
134
            $path = explode('.', $path);
135
        }
136
137
        $selection = &$this->schema;
138 3
        foreach ($path as $i => $subSelector) {
139 3
            if (is_array($selection)) {
140 3
                if (!isset($selection[$subSelector])) {
141
                    $selection[$subSelector] = [];
142
                }
143 3
            } elseif ($selection instanceof Schema) {
144 3
                $selection->setField(array_slice($path, $i), $value);
145 3
                return $this;
146 3
            } else {
147 3
                $selection = [$subSelector => []];
148
            }
149 1
            $selection = &$selection[$subSelector];
150 1
        }
151 1
152
        $selection = $value;
153
        return $this;
154
    }
155 3
156
    /**
157
     * Get the ID for the schema.
158 3
     *
159 3
     * @return string
160
     */
161
    public function getID(): string {
162
        return isset($this->schema['id']) ? $this->schema['id'] : '';
163
    }
164
165
    /**
166
     * Set the ID for the schema.
167 3
     *
168 3
     * @param string $id The new ID.
169
     * @throws \InvalidArgumentException Throws an exception when the provided ID is not a string.
170
     * @return Schema
171
     */
172
    public function setID(string $id) {
173
        if (is_string($id)) {
174
            $this->schema['id'] = $id;
175
        } else {
176
            throw new \InvalidArgumentException("The ID is not a valid string.", 500);
177
        }
178 1
179 1
        return $this;
180 1
    }
181
182
    /**
183
     * Return the validation flags.
184
     *
185 1
     * @return int Returns a bitwise combination of flags.
186
     */
187
    public function getFlags(): int {
188
        return $this->flags;
189
    }
190
191
    /**
192
     * Set the validation flags.
193 1
     *
194 1
     * @param int $flags One or more of the **Schema::FLAG_*** constants.
195
     * @return Schema Returns the current instance for fluent calls.
196
     */
197
    public function setFlags(int $flags) {
198
        if (!is_int($flags)) {
199
            throw new \InvalidArgumentException('Invalid flags.', 500);
200
        }
201
        $this->flags = $flags;
202
203 8
        return $this;
204 8
    }
205 1
206
    /**
207 7
     * Whether or not the schema has a flag (or combination of flags).
208
     *
209 7
     * @param int $flag One or more of the **Schema::VALIDATE_*** constants.
210
     * @return bool Returns **true** if all of the flags are set or **false** otherwise.
211
     */
212
    public function hasFlag(int $flag): bool {
213
        return ($this->flags & $flag) === $flag;
214
    }
215
216
    /**
217
     * Set a flag.
218 12
     *
219 12
     * @param int $flag One or more of the **Schema::VALIDATE_*** constants.
220
     * @param bool $value Either true or false.
221
     * @return $this
222
     */
223
    public function setFlag(int $flag, bool $value) {
224
        if ($value) {
225
            $this->flags = $this->flags | $flag;
226
        } else {
227
            $this->flags = $this->flags & ~$flag;
228
        }
229 1
        return $this;
230 1
    }
231 1
232
    /**
233 1
     * Merge a schema with this one.
234
     *
235 1
     * @param Schema $schema A scheme instance. Its parameters will be merged into the current instance.
236
     * @return $this
237
     */
238
    public function merge(Schema $schema) {
239
        $this->mergeInternal($this->schema, $schema->getSchemaArray(), true, true);
240
        return $this;
241
    }
242
243
    /**
244 4
     * Add another schema to this one.
245 4
     *
246 4
     * Adding schemas together is analogous to array addition. When you add a schema it will only add missing information.
247
     *
248
     * @param Schema $schema The schema to add.
249
     * @param bool $addProperties Whether to add properties that don't exist in this schema.
250
     * @return $this
251
     */
252
    public function add(Schema $schema, $addProperties = false) {
253
        $this->mergeInternal($this->schema, $schema->getSchemaArray(), false, $addProperties);
254
        return $this;
255
    }
256
257
    /**
258 4
     * The internal implementation of schema merging.
259 4
     *
260 4
     * @param array &$target The target of the merge.
261
     * @param array $source The source of the merge.
262
     * @param bool $overwrite Whether or not to replace values.
263
     * @param bool $addProperties Whether or not to add object properties to the target.
264
     * @return array
265
     */
266
    private function mergeInternal(array &$target, array $source, $overwrite = true, $addProperties = true) {
267
        // We need to do a fix for required properties here.
268
        if (isset($target['properties']) && !empty($source['required'])) {
269
            $required = isset($target['required']) ? $target['required'] : [];
270
271
            if (isset($source['required']) && $addProperties) {
272 7
                $newProperties = array_diff(array_keys($source['properties']), array_keys($target['properties']));
273
                $newRequired = array_intersect($source['required'], $newProperties);
274 7
275 5
                $required = array_merge($required, $newRequired);
276
            }
277 5
        }
278 4
279 4
280
        foreach ($source as $key => $val) {
281 4
            if (is_array($val) && array_key_exists($key, $target) && is_array($target[$key])) {
282
                if ($key === 'properties' && !$addProperties) {
283
                    // We just want to merge the properties that exist in the destination.
284
                    foreach ($val as $name => $prop) {
285
                        if (isset($target[$key][$name])) {
286 7
                            $targetProp = &$target[$key][$name];
287 7
288 7
                            if (is_array($targetProp) && is_array($prop)) {
289
                                $this->mergeInternal($targetProp, $prop, $overwrite, $addProperties);
290 2
                            } elseif (is_array($targetProp) && $prop instanceof Schema) {
291 2
                                $this->mergeInternal($targetProp, $prop->getSchemaArray(), $overwrite, $addProperties);
292 2
                            } elseif ($overwrite) {
293
                                $targetProp = $prop;
294 2
                            }
295 2
                        }
296 1
                    }
297
                } elseif (isset($val[0]) || isset($target[$key][0])) {
298 1
                    if ($overwrite) {
299 2
                        // This is a numeric array, so just do a merge.
300
                        $merged = array_merge($target[$key], $val);
301
                        if (is_string($merged[0])) {
302
                            $merged = array_keys(array_flip($merged));
303 7
                        }
304 5
                        $target[$key] = $merged;
305
                    }
306 3
                } else {
307 3
                    $target[$key] = $this->mergeInternal($target[$key], $val, $overwrite, $addProperties);
308 3
                }
309
            } elseif (!$overwrite && array_key_exists($key, $target) && !is_array($val)) {
310 5
                // Do nothing, we aren't replacing.
311
            } else {
312
                $target[$key] = $val;
313 7
            }
314
        }
315 7
316
        if (isset($required)) {
317
            if (empty($required)) {
318 7
                unset($target['required']);
319
            } else {
320
                $target['required'] = $required;
321
            }
322 7
        }
323 5
324 1
        return $target;
325
    }
326 5
327
//    public function overlay(Schema $schema )
328
329
    /**
330 7
     * Returns the internal schema array.
331
     *
332
     * @return array
333
     * @see Schema::jsonSerialize()
334
     */
335
    public function getSchemaArray(): array {
336
        return $this->schema;
337
    }
338
339
    /**
340
     * Parse a short schema and return the associated schema.
341 10
     *
342 10
     * @param array $arr The schema array.
343
     * @param mixed[] $args Constructor arguments for the schema instance.
344
     * @return static Returns a new schema.
345
     */
346
    public static function parse(array $arr, ...$args) {
347
        $schema = new static([], ...$args);
348
        $schema->schema = $schema->parseInternal($arr);
349
        return $schema;
350
    }
351
352 145
    /**
353 145
     * Parse a schema in short form into a full schema array.
354 145
     *
355 145
     * @param array $arr The array to parse into a schema.
356
     * @return array The full schema array.
357
     * @throws \InvalidArgumentException Throws an exception when an item in the schema is invalid.
358
     */
359
    protected function parseInternal(array $arr): array {
360
        if (empty($arr)) {
361
            // An empty schema validates to anything.
362
            return [];
363
        } elseif (isset($arr['type'])) {
364
            // This is a long form schema and can be parsed as the root.
365 145
            return $this->parseNode($arr);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->parseNode($arr) could return the type ArrayAccess which is incompatible with the type-hinted return array. Consider adding an additional type-check to rule them out.
Loading history...
366 145
        } else {
367
            // Check for a root schema.
368 7
            $value = reset($arr);
369 139
            $key = key($arr);
370
            if (is_int($key)) {
371
                $key = $value;
372
                $value = null;
373
            }
374 139
            list ($name, $param) = $this->parseShortParam($key, $value);
375 139
            if (empty($name)) {
376 139
                return $this->parseNode($param, $value);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->parseNode($param, $value) could return the type ArrayAccess which is incompatible with the type-hinted return array. Consider adding an additional type-check to rule them out.
Loading history...
377 83
            }
378 83
        }
379
380 139
        // If we are here then this is n object schema.
381 139
        list($properties, $required) = $this->parseProperties($arr);
382 48
383
        $result = [
384
            'type' => 'object',
385
            'properties' => $properties,
386
            'required' => $required
387 94
        ];
388
389
        return array_filter($result);
390 94
    }
391 94
392 94
    /**
393
     * Parse a schema node.
394
     *
395 94
     * @param array $node The node to parse.
396
     * @param mixed $value Additional information from the node.
397
     * @return array|\ArrayAccess Returns a JSON schema compatible node.
398
     */
399
    private function parseNode($node, $value = null) {
400
        if (is_array($value)) {
401
            // The value describes a bit more about the schema.
402
            switch ($node['type']) {
403
                case 'array':
404
                    if (isset($value['items'])) {
405 139
                        // The value includes array schema information.
406 139
                        $node = array_replace($node, $value);
407
                    } else {
408 59
                        $node['items'] = $this->parseInternal($value);
409 59
                    }
410 11
                    break;
411
                case 'object':
412 4
                    // The value is a schema of the object.
413
                    if (isset($value['properties'])) {
414 7
                        list($node['properties']) = $this->parseProperties($value['properties']);
415
                    } else {
416 11
                        list($node['properties'], $required) = $this->parseProperties($value);
417 49
                        if (!empty($required)) {
418
                            $node['required'] = $required;
419 12
                        }
420
                    }
421
                    break;
422 12
                default:
423 12
                    $node = array_replace($node, $value);
424 12
                    break;
425
            }
426
        } elseif (is_string($value)) {
427 12
            if ($node['type'] === 'array' && $arrType = $this->getType($value)) {
428
                $node['items'] = ['type' => $arrType];
429 37
            } elseif (!empty($value)) {
430 59
                $node['description'] = $value;
431
            }
432 100
        } elseif ($value === null) {
433 80
            // Parse child elements.
434 6
            if ($node['type'] === 'array' && isset($node['items'])) {
435 76
                // The value includes array schema information.
436 80
                $node['items'] = $this->parseInternal($node['items']);
437
            } elseif ($node['type'] === 'object' && isset($node['properties'])) {
438 25
                list($node['properties']) = $this->parseProperties($node['properties']);
439
440 21
            }
441
        }
442
443 21
        if (is_array($node)) {
444
            if (!empty($node['allowNull'])) {
445
                $node['type'] = array_merge((array)$node['type'], ['null']);
446
            }
447
            unset($node['allowNull']);
448
449 139
            if ($node['type'] === null || $node['type'] === []) {
450 138
                unset($node['type']);
451 1
            }
452
        }
453 138
454
        return $node;
455 138
    }
456 4
457
    /**
458
     * Parse the schema for an object's properties.
459
     *
460 139
     * @param array $arr An object property schema.
461
     * @return array Returns a schema array suitable to be placed in the **properties** key of a schema.
462
     */
463
    private function parseProperties(array $arr): array {
464
        $properties = [];
465
        $requiredProperties = [];
466
        foreach ($arr as $key => $value) {
467
            // Fix a schema specified as just a value.
468
            if (is_int($key)) {
469 94
                if (is_string($value)) {
470 94
                    $key = $value;
471 94
                    $value = '';
472 94
                } else {
473
                    throw new \InvalidArgumentException("Schema at position $key is not a valid parameter.", 500);
474 94
                }
475 67
            }
476 67
477 67
            // The parameter is defined in the key.
478
            list($name, $param, $required) = $this->parseShortParam($key, $value);
479
480
            $node = $this->parseNode($param, $value);
481
482
            $properties[$name] = $node;
483
            if ($required) {
484 94
                $requiredProperties[] = $name;
485
            }
486 94
        }
487
        return [$properties, $requiredProperties];
488 94
    }
489 94
490 94
    /**
491
     * Parse a short parameter string into a full array parameter.
492
     *
493 94
     * @param string $key The short parameter string to parse.
494
     * @param array $value An array of other information that might help resolve ambiguity.
495
     * @return array Returns an array in the form `[string name, array param, bool required]`.
496
     * @throws \InvalidArgumentException Throws an exception if the short param is not in the correct format.
497
     */
498
    public function parseShortParam(string $key, $value = []): array {
499
        // Is the parameter optional?
500
        if (substr($key, -1) === '?') {
501
            $required = false;
502
            $key = substr($key, 0, -1);
503
        } else {
504 139
            $required = true;
505
        }
506 139
507 63
        // Check for a type.
508 63
        $parts = explode(':', $key);
509
        $name = $parts[0];
510 99
        $types = [];
511
512
        if (!empty($parts[1])) {
513
            $shortTypes = explode('|', $parts[1]);
514 139
            foreach ($shortTypes as $alias) {
515 139
                $found = $this->getType($alias);
516 139
                if ($found === null) {
517
                    throw new \InvalidArgumentException("Unknown type '$alias'", 500);
518 139
                } else {
519 134
                    $types[] = $found;
520 134
                }
521 134
            }
522 134
        }
523
524
        if ($value instanceof Schema) {
525 134
            if (count($types) === 1 && $types[0] === 'array') {
526
                $param = ['type' => $types[0], 'items' => $value];
527
            } else {
528
                $param = $value;
529
            }
530 139
        } elseif (isset($value['type'])) {
531 5
            $param = $value;
532 1
533
            if (!empty($types) && $types !== (array)$param['type']) {
534 5
                $typesStr = implode('|', $types);
535
                $paramTypesStr = implode('|', (array)$param['type']);
536 138
537 3
                throw new \InvalidArgumentException("Type mismatch between $typesStr and {$paramTypesStr} for field $name.", 500);
538
            }
539 3
        } else {
540
            if (empty($types) && !empty($parts[1])) {
541
                throw new \InvalidArgumentException("Invalid type {$parts[1]} for field $name.", 500);
542
            }
543 3
            if (empty($types)) {
544
                $param = ['type' => null];
545
            } else {
546 135
                $param = ['type' => count($types) === 1 ? $types[0] : $types];
547
            }
548
549 135
            // Parsed required strings have a minimum length of 1.
550 4
            if (in_array('string', $types) && !empty($name) && $required && (!isset($value['default']) || $value['default'] !== '')) {
551
                $param['minLength'] = 1;
552 134
            }
553
        }
554
555
        return [$name, $param, $required];
556 135
    }
557 38
558
    /**
559
     * Add a custom filter to change data before validation.
560
     *
561 139
     * @param string $fieldname The name of the field to filter, if any.
562
     *
563
     * If you are adding a filter to a deeply nested field then separate the path with dots.
564
     * @param callable $callback The callback to filter the field.
565
     * @return $this
566
     */
567
    public function addFilter(string $fieldname, callable $callback) {
568
        $this->filters[$fieldname][] = $callback;
569
        return $this;
570
    }
571
572
    /**
573 1
     * Add a custom validator to to validate the schema.
574 1
     *
575 1
     * @param string $fieldname The name of the field to validate, if any.
576
     *
577
     * If you are adding a validator to a deeply nested field then separate the path with dots.
578
     * @param callable $callback The callback to validate with.
579
     * @return Schema Returns `$this` for fluent calls.
580
     */
581
    public function addValidator(string $fieldname, callable $callback) {
582
        $this->validators[$fieldname][] = $callback;
583
        return $this;
584
    }
585
586
    /**
587 4
     * Require one of a given set of fields in the schema.
588 4
     *
589 4
     * @param array $required The field names to require.
590
     * @param string $fieldname The name of the field to attach to.
591
     * @param int $count The count of required items.
592
     * @return Schema Returns `$this` for fluent calls.
593
     */
594
    public function requireOneOf(array $required, string $fieldname = '', int $count = 1) {
595
        $result = $this->addValidator(
596
            $fieldname,
597
            function ($data, ValidationField $field) use ($required, $count) {
598
                // This validator does not apply to sparse validation.
599
                if ($field->isSparse()) {
600 3
                    return true;
601 3
                }
602 3
603 3
                $hasCount = 0;
604
                $flattened = [];
605 3
606 1
                foreach ($required as $name) {
607
                    $flattened = array_merge($flattened, (array)$name);
608
609 2
                    if (is_array($name)) {
610 2
                        // This is an array of required names. They all must match.
611
                        $hasCountInner = 0;
612 2
                        foreach ($name as $nameInner) {
613 2
                            if (array_key_exists($nameInner, $data)) {
614
                                $hasCountInner++;
615 2
                            } else {
616
                                break;
617 1
                            }
618 1
                        }
619 1
                        if ($hasCountInner >= count($name)) {
620 1
                            $hasCount++;
621
                        }
622 1
                    } elseif (array_key_exists($name, $data)) {
623
                        $hasCount++;
624
                    }
625 1
626 1
                    if ($hasCount >= $count) {
627
                        return true;
628 2
                    }
629 1
                }
630
631
                if ($count === 1) {
632 2
                    $message = 'One of {required} are required.';
633 2
                } else {
634
                    $message = '{count} of {required} are required.';
635
                }
636
637 2
                $field->addError('missingField', [
638 1
                    'messageCode' => $message,
639
                    'required' => $required,
640 1
                    'count' => $count
641
                ]);
642
                return false;
643 2
            }
644 2
        );
645 2
646 2
        return $result;
647
    }
648 2
649 3
    /**
650
     * Validate data against the schema.
651
     *
652 3
     * @param mixed $data The data to validate.
653
     * @param bool $sparse Whether or not this is a sparse validation.
654
     * @return mixed Returns a cleaned version of the data.
655
     * @throws ValidationException Throws an exception when the data does not validate against the schema.
656
     */
657
    public function validate($data, $sparse = false) {
658
        $field = new ValidationField($this->createValidation(), $this->schema, '', $sparse);
659
660
        $clean = $this->validateField($data, $field, $sparse);
661
662
        if (Invalid::isInvalid($clean) && $field->isValid()) {
663 145
            // This really shouldn't happen, but we want to protect against seeing the invalid object.
664 145
            $field->addError('invalid', ['messageCode' => '{field} is invalid.', 'status' => 422]);
665
        }
666 145
667
        if (!$field->getValidation()->isValid()) {
668 143
            throw new ValidationException($field->getValidation());
669
        }
670
671
        return $clean;
672
    }
673 143
674 54
    /**
675
     * Validate data against the schema and return the result.
676
     *
677 103
     * @param mixed $data The data to validate.
678
     * @param bool $sparse Whether or not to do a sparse validation.
679
     * @return bool Returns true if the data is valid. False otherwise.
680
     */
681
    public function isValid($data, $sparse = false) {
682
        try {
683
            $this->validate($data, $sparse);
684
            return true;
685
        } catch (ValidationException $ex) {
686
            return false;
687 21
        }
688
    }
689 21
690 17
    /**
691 12
     * Validate a field.
692 12
     *
693
     * @param mixed $value The value to validate.
694
     * @param ValidationField $field A validation object to add errors to.
695
     * @param bool $sparse Whether or not this is a sparse validation.
696
     * @return mixed|Invalid Returns a clean version of the value with all extra fields stripped out or invalid if the value
697
     * is completely invalid.
698
     */
699
    protected function validateField($value, ValidationField $field, $sparse = false) {
700
        $result = $value = $this->filterField($value, $field);
701
702
        if ($field->getField() instanceof Schema) {
703
            try {
704
                $result = $field->getField()->validate($value, $sparse);
705 145
            } catch (ValidationException $ex) {
706 145
                // The validation failed, so merge the validations together.
707
                $field->getValidation()->merge($ex->getValidation(), $field->getName());
708 145
            }
709
        } elseif (($value === null || ($value === '' && !$field->hasType('string'))) && $field->hasType('null')) {
710 5
            $result = null;
711 2
        } else {
712
            // Validate the field's type.
713 5
            $type = $field->getType();
714
            if (is_array($type)) {
715 145
                $result = $this->validateMultipleTypes($value, $type, $field, $sparse);
716 7
            } else {
717
                $result = $this->validateSingleType($value, $type, $field, $sparse);
718
            }
719 144
            if (Invalid::isValid($result)) {
720 144
                $result = $this->validateEnum($result, $field);
721 24
            }
722
        }
723 121
724
        // Validate a custom field validator.
725 144
        if (Invalid::isValid($result)) {
726 142
            $this->callValidators($result, $field);
727
        }
728
729
        return $result;
730
    }
731 145
732 143
    /**
733
     * Validate an array.
734
     *
735 145
     * @param mixed $value The value to validate.
736
     * @param ValidationField $field The validation results to add.
737
     * @param bool $sparse Whether or not this is a sparse validation.
738
     * @return array|Invalid Returns an array or invalid if validation fails.
739
     */
740
    protected function validateArray($value, ValidationField $field, $sparse = false) {
741
        if ((!is_array($value) || (count($value) > 0 && !array_key_exists(0, $value))) && !$value instanceof \Traversable) {
742
            $field->addTypeError('array');
743
            return Invalid::value();
744
        } else {
745
            if ((null !== $minItems = $field->val('minItems')) && count($value) < $minItems) {
746 20
                $field->addError(
747 20
                    'minItems',
748 5
                    [
749 5
                        'messageCode' => '{field} must contain at least {minItems} {minItems,plural,item}.',
750
                        'minItems' => $minItems,
751 16
                        'status' => 422
752 1
                    ]
753 1
                );
754
            }
755 1
            if ((null !== $maxItems = $field->val('maxItems')) && count($value) > $maxItems) {
756 1
                $field->addError(
757 1
                    'maxItems',
758
                    [
759
                        'messageCode' => '{field} must contain no more than {maxItems} {maxItems,plural,item}.',
760
                        'maxItems' => $maxItems,
761 16
                        'status' => 422
762 1
                    ]
763 1
                );
764
            }
765 1
766 1
            if ($field->val('items') !== null) {
767 1
                $result = [];
768
769
                // Validate each of the types.
770
                $itemValidation = new ValidationField(
771
                    $field->getValidation(),
772 16
                    $field->val('items'),
773 12
                    '',
774
                    $sparse
775
                );
776 12
777 12
                $count = 0;
778 12
                foreach ($value as $i => $item) {
779 12
                    $itemValidation->setName($field->getName()."[{$i}]");
780 12
                    $validItem = $this->validateField($item, $itemValidation, $sparse);
781
                    if (Invalid::isValid($validItem)) {
782
                        $result[] = $validItem;
783 12
                    }
784 12
                    $count++;
785 12
                }
786 12
787 12
                return empty($result) && $count > 0 ? Invalid::value() : $result;
788 12
            } else {
789
                // Cast the items into a proper numeric array.
790 12
                $result = is_array($value) ? array_values($value) : iterator_to_array($value);
791
                return $result;
792
            }
793 12
        }
794
    }
795
796 4
    /**
797 4
     * Validate a boolean value.
798
     *
799
     * @param mixed $value The value to validate.
800
     * @param ValidationField $field The validation results to add.
801
     * @return bool|Invalid Returns the cleaned value or invalid if validation fails.
802
     */
803
    protected function validateBoolean($value, ValidationField $field) {
804
        $value = $value === null ? $value : filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
805
        if ($value === null) {
806
            $field->addTypeError('boolean');
807
            return Invalid::value();
808
        }
809 28
810 28
        return $value;
811 28
    }
812 4
813 4
    /**
814
     * Validate a date time.
815
     *
816 25
     * @param mixed $value The value to validate.
817
     * @param ValidationField $field The validation results to add.
818
     * @return \DateTimeInterface|Invalid Returns the cleaned value or **null** if it isn't valid.
819
     */
820
    protected function validateDatetime($value, ValidationField $field) {
821
        if ($value instanceof \DateTimeInterface) {
822
            // do nothing, we're good
823
        } elseif (is_string($value) && $value !== '' && !is_numeric($value)) {
824
            try {
825
                $dt = new \DateTimeImmutable($value);
826 11
                if ($dt) {
827 11
                    $value = $dt;
828
                } else {
829 10
                    $value = null;
830
                }
831 7
            } catch (\Throwable $ex) {
832 6
                $value = Invalid::value();
833 6
            }
834
        } elseif (is_int($value) && $value > 0) {
835 6
            try {
836
                $value = new \DateTimeImmutable('@'.(string)round($value));
837 1
            } catch (\Throwable $ex) {
838 7
                $value = Invalid::value();
839
            }
840 3
        } else {
841 1
            $value = Invalid::value();
842
        }
843 2
844
        if (Invalid::isInvalid($value)) {
845
            $field->addTypeError('datetime');
846 11
        }
847 3
        return $value;
848
    }
849 11
850
    /**
851
     * Validate a float.
852
     *
853
     * @param mixed $value The value to validate.
854
     * @param ValidationField $field The validation results to add.
855
     * @return float|Invalid Returns a number or **null** if validation fails.
856
     */
857
    protected function validateNumber($value, ValidationField $field) {
858
        $result = filter_var($value, FILTER_VALIDATE_FLOAT);
859 10
        if ($result === false) {
860 10
            $field->addTypeError('number');
861 10
            return Invalid::value();
862 3
        }
863 3
        return $result;
864
    }
865 7
    /**
866
     * Validate and integer.
867
     *
868
     * @param mixed $value The value to validate.
869
     * @param ValidationField $field The validation results to add.
870
     * @return int|Invalid Returns the cleaned value or **null** if validation fails.
871
     */
872
    protected function validateInteger($value, ValidationField $field) {
873
        $result = filter_var($value, FILTER_VALIDATE_INT);
874 35
875 35
        if ($result === false) {
876
            $field->addTypeError('integer');
877 35
            return Invalid::value();
878 8
        }
879 8
        return $result;
880
    }
881 31
882
    /**
883
     * Validate an object.
884
     *
885
     * @param mixed $value The value to validate.
886
     * @param ValidationField $field The validation results to add.
887
     * @param bool $sparse Whether or not this is a sparse validation.
888
     * @return object|Invalid Returns a clean object or **null** if validation fails.
889
     */
890
    protected function validateObject($value, ValidationField $field, $sparse = false) {
891
        if (!$this->isArray($value) || isset($value[0])) {
892 83
            $field->addTypeError('object');
893 83
            return Invalid::value();
894 5
        } elseif (is_array($field->val('properties'))) {
895 5
            // Validate the data against the internal schema.
896 83
            $value = $this->validateProperties($value, $field, $sparse);
897
        } elseif (!is_array($value)) {
898 80
            $value = $this->toObjectArray($value);
899 3
        }
900 3
        return $value;
901
    }
902 81
903
    /**
904
     * Validate data against the schema and return the result.
905
     *
906
     * @param array|\Traversable&\ArrayAccess $data The data to validate.
907
     * @param ValidationField $field This argument will be filled with the validation result.
908
     * @param bool $sparse Whether or not this is a sparse validation.
909
     * @return array|Invalid Returns a clean array with only the appropriate properties and the data coerced to proper types.
910
     * or invalid if there are no valid properties.
911
     */
912
    protected function validateProperties($data, ValidationField $field, $sparse = false) {
913
        $properties = $field->val('properties', []);
914 80
        $required = array_flip($field->val('required', []));
915 80
916 80
        if (is_array($data)) {
0 ignored issues
show
The condition is_array($data) is always false.
Loading history...
917
            $keys = array_keys($data);
918 80
            $clean = [];
919 76
        } else {
920 76
            $keys = array_keys(iterator_to_array($data));
0 ignored issues
show
It seems like $data can also be of type ArrayAccess; however, parameter $iterator of iterator_to_array() does only seem to accept Traversable, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

920
            $keys = array_keys(iterator_to_array(/** @scrutinizer ignore-type */ $data));
Loading history...
921
            $class = get_class($data);
922 4
            $clean = new $class;
923 4
924 4
            if ($clean instanceof \ArrayObject && $data instanceof \ArrayObject) {
925
                $clean->setFlags($data->getFlags());
926 4
                $clean->setIteratorClass($data->getIteratorClass());
927 3
            }
928 3
        }
929
        $keys = array_combine(array_map('strtolower', $keys), $keys);
930
931 80
        $propertyField = new ValidationField($field->getValidation(), [], null, $sparse);
932
933 80
        // Loop through the schema fields and validate each one.
934
        foreach ($properties as $propertyName => $property) {
935
            $propertyField
936 80
                ->setField($property)
937
                ->setName(ltrim($field->getName().".$propertyName", '.'));
938 80
939 80
            $lName = strtolower($propertyName);
940
            $isRequired = isset($required[$propertyName]);
941 80
942 80
            // First check for required fields.
943
            if (!array_key_exists($lName, $keys)) {
944
                if ($sparse) {
945 80
                    // Sparse validation can leave required fields out.
946 19
                } elseif ($propertyField->hasVal('default')) {
947
                    $clean[$propertyName] = $propertyField->val('default');
948 18
                } elseif ($isRequired) {
949 2
                    $propertyField->addError('missingField', ['messageCode' => '{field} is required.']);
950 16
                }
951 19
            } else {
952
                $value = $data[$keys[$lName]];
953
954 77
                if (in_array($value, [null, ''], true) && !$isRequired && !$propertyField->hasType('null')) {
955
                    if ($propertyField->getType() !== 'string' || $value === null) {
956 77
                        continue;
957 5
                    }
958 2
                }
959
960
                $clean[$propertyName] = $this->validateField($value, $propertyField, $sparse);
961
            }
962 75
963
            unset($keys[$lName]);
964
        }
965 78
966
        // Look for extraneous properties.
967
        if (!empty($keys)) {
968
            if ($this->hasFlag(Schema::VALIDATE_EXTRA_PROPERTY_NOTICE)) {
969 80
                $msg = sprintf("%s has unexpected field(s): %s.", $field->getName() ?: 'value', implode(', ', $keys));
970 11
                trigger_error($msg, E_USER_NOTICE);
971 2
            }
972 2
973
            if ($this->hasFlag(Schema::VALIDATE_EXTRA_PROPERTY_EXCEPTION)) {
974
                $field->addError('invalid', [
975 9
                    'messageCode' => '{field} has {extra,plural,an unexpected field,unexpected fields}: {extra}.',
976 2
                    'extra' => array_values($keys),
977 2
                    'status' => 422
978 2
                ]);
979 2
            }
980
        }
981
982
        return $clean;
983
    }
984 78
985
    /**
986
     * Validate a string.
987
     *
988
     * @param mixed $value The value to validate.
989
     * @param ValidationField $field The validation results to add.
990
     * @return string|Invalid Returns the valid string or **null** if validation fails.
991
     */
992
    protected function validateString($value, ValidationField $field) {
993
        if (is_string($value) || is_numeric($value)) {
994 63
            $value = $result = (string)$value;
995 63
        } else {
996 61
            $field->addTypeError('string');
997
            return Invalid::value();
998 4
        }
999 4
1000
        if (($minLength = $field->val('minLength', 0)) > 0 && mb_strlen($value) < $minLength) {
1001
            if (!empty($field->getName()) && $minLength === 1) {
1002 61
                $field->addError('missingField', ['messageCode' => '{field} is required.', 'status' => 422]);
1003 61
            } else {
1004 3
                $field->addError(
1005 1
                    'minLength',
1006
                    [
1007 2
                        'messageCode' => '{field} should be at least {minLength} {minLength,plural,character} long.',
1008 2
                        'minLength' => $minLength,
1009
                        'status' => 422
1010 2
                    ]
1011 2
                );
1012 2
            }
1013
        }
1014
        if (($maxLength = $field->val('maxLength', 0)) > 0 && mb_strlen($value) > $maxLength) {
1015
            $field->addError(
1016
                'maxLength',
1017 61
                [
1018 1
                    'messageCode' => '{field} is {overflow} {overflow,plural,characters} too long.',
1019 1
                    'maxLength' => $maxLength,
1020
                    'overflow' => mb_strlen($value) - $maxLength,
1021 1
                    'status' => 422
1022 1
                ]
1023 1
            );
1024 1
        }
1025
        if ($pattern = $field->val('pattern')) {
1026
            $regex = '`'.str_replace('`', preg_quote('`', '`'), $pattern).'`';
1027
1028 61
            if (!preg_match($regex, $value)) {
1029 4
                $field->addError(
1030
                    'invalid',
1031 4
                    [
1032 2
                        'messageCode' => '{field} is in the incorrect format.',
1033 2
                        'status' => 422
1034
                    ]
1035 2
                );
1036
            }
1037
        }
1038
        if ($format = $field->val('format')) {
1039
            $type = $format;
1040
            switch ($format) {
1041 61
                case 'date-time':
1042 15
                    $result = $this->validateDatetime($result, $field);
1043
                    if ($result instanceof \DateTimeInterface) {
1044 15
                        $result = $result->format(\DateTime::RFC3339);
1045 4
                    }
1046 4
                    break;
1047 4
                case 'email':
1048
                    $result = filter_var($result, FILTER_VALIDATE_EMAIL);
1049 4
                    break;
1050 11
                case 'ipv4':
1051 1
                    $type = 'IPv4 address';
1052 1
                    $result = filter_var($result, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
1053 10
                    break;
1054 1
                case 'ipv6':
1055 1
                    $type = 'IPv6 address';
1056 1
                    $result = filter_var($result, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
1057 9
                    break;
1058 1
                case 'ip':
1059 1
                    $type = 'IP address';
1060 1
                    $result = filter_var($result, FILTER_VALIDATE_IP);
1061 8
                    break;
1062 1
                case 'uri':
1063 1
                    $type = 'URI';
1064 1
                    $result = filter_var($result, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED | FILTER_FLAG_SCHEME_REQUIRED);
1065 7
                    break;
1066 7
                default:
1067 7
                    trigger_error("Unrecognized format '$format'.", E_USER_NOTICE);
1068 7
            }
1069
            if ($result === false) {
1070
                $field->addTypeError($type);
1071
            }
1072 15
        }
1073 5
1074
        if ($field->isValid()) {
1075
            return $result;
1076
        } else {
1077 61
            return Invalid::value();
1078 54
        }
1079
    }
1080 11
1081
    /**
1082
     * Validate a unix timestamp.
1083
     *
1084
     * @param mixed $value The value to validate.
1085
     * @param ValidationField $field The field being validated.
1086
     * @return int|Invalid Returns a valid timestamp or invalid if the value doesn't validate.
1087
     */
1088
    protected function validateTimestamp($value, ValidationField $field) {
1089
        if (is_numeric($value) && $value > 0) {
1090
            $result = (int)$value;
1091 5
        } elseif (is_string($value) && $ts = strtotime($value)) {
1092 5
            $result = $ts;
1093 1
        } else {
1094 4
            $field->addTypeError('timestamp');
1095 1
            $result = Invalid::value();
1096
        }
1097 3
        return $result;
1098 3
    }
1099
1100 5
    /**
1101
     * Validate a null value.
1102
     *
1103
     * @param mixed $value The value to validate.
1104
     * @param ValidationField $field The error collector for the field.
1105
     * @return null|Invalid Returns **null** or invalid.
1106
     */
1107
    protected function validateNull($value, ValidationField $field) {
1108
        if ($value === null) {
1109
            return null;
1110 1
        }
1111 1
        $field->addError('invalid', ['messageCode' => '{field} should be null.', 'status' => 422]);
1112
        return Invalid::value();
1113
    }
1114 1
1115 1
    /**
1116
     * Validate a value against an enum.
1117
     *
1118
     * @param mixed $value The value to test.
1119
     * @param ValidationField $field The validation object for adding errors.
1120
     * @return mixed|Invalid Returns the value if it is one of the enumerated values or invalid otherwise.
1121
     */
1122
    protected function validateEnum($value, ValidationField $field) {
1123
        $enum = $field->val('enum');
1124
        if (empty($enum)) {
1125 142
            return $value;
1126 142
        }
1127 142
1128 141
        if (!in_array($value, $enum, true)) {
1129
            $field->addError(
1130
                'invalid',
1131 1
                [
1132 1
                    'messageCode' => '{field} must be one of: {enum}.',
1133 1
                    'enum' => $enum,
1134
                    'status' => 422
1135 1
                ]
1136 1
            );
1137 1
            return Invalid::value();
1138
        }
1139
        return $value;
1140 1
    }
1141
1142 1
    /**
1143
     * Call all of the filters attached to a field.
1144
     *
1145
     * @param mixed $value The field value being filtered.
1146
     * @param ValidationField $field The validation object.
1147
     * @return mixed Returns the filtered value. If there are no filters for the field then the original value is returned.
1148
     */
1149
    protected function callFilters($value, ValidationField $field) {
1150
        // Strip array references in the name except for the last one.
1151
        $key = preg_replace(['`\[\d+\]$`', '`\[\d+\]`'], ['[]', ''], $field->getName());
1152 145
        if (!empty($this->filters[$key])) {
1153
            foreach ($this->filters[$key] as $filter) {
1154 145
                $value = call_user_func($filter, $value, $field);
1155 145
            }
1156 1
        }
1157 1
        return $value;
1158
    }
1159
1160 145
    /**
1161
     * Call all of the validators attached to a field.
1162
     *
1163
     * @param mixed $value The field value being validated.
1164
     * @param ValidationField $field The validation object to add errors.
1165
     */
1166
    protected function callValidators($value, ValidationField $field) {
1167
        $valid = true;
1168
1169 143
        // Strip array references in the name except for the last one.
1170 143
        $key = preg_replace(['`\[\d+\]$`', '`\[\d+\]`'], ['[]', ''], $field->getName());
1171
        if (!empty($this->validators[$key])) {
1172
            foreach ($this->validators[$key] as $validator) {
1173 143
                $r = call_user_func($validator, $value, $field);
1174 143
1175 4
                if ($r === false || Invalid::isInvalid($r)) {
1176 4
                    $valid = false;
1177
                }
1178 4
            }
1179 4
        }
1180
1181
        // Add an error on the field if the validator hasn't done so.
1182
        if (!$valid && $field->isValid()) {
1183
            $field->addError('invalid', ['messageCode' => '{field} is invalid.', 'status' => 422]);
1184
        }
1185 143
    }
1186
1187
    /**
1188 143
     * Specify data which should be serialized to JSON.
1189
     *
1190
     * This method specifically returns data compatible with the JSON schema format.
1191
     *
1192
     * @return mixed Returns data which can be serialized by **json_encode()**, which is a value of any type other than a resource.
1193
     * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
1194
     * @link http://json-schema.org/
1195
     */
1196
    public function jsonSerialize() {
1197
        $fix = function ($schema) use (&$fix) {
1198
            if ($schema instanceof Schema) {
1199
                return $schema->jsonSerialize();
1200 16
            }
1201 16
1202 1
            if (!empty($schema['type'])) {
1203
                $types = (array)$schema['type'];
1204
1205 16
                foreach ($types as $i => &$type) {
1206 15
                    // Swap datetime and timestamp to other types with formats.
1207
                    if ($type === 'datetime') {
1208 15
                        $type = 'string';
1209
                        $schema['format'] = 'date-time';
1210 15
                    } elseif ($schema['type'] === 'timestamp') {
1211 5
                        $type = 'integer';
1212 5
                        $schema['format'] = 'timestamp';
1213 14
                    }
1214 3
                }
1215 15
                $types = array_unique($types);
1216
                $schema['type'] = count($types) === 1 ? reset($types) : $types;
1217
            }
1218 15
1219 15
            if (!empty($schema['items'])) {
1220
                $schema['items'] = $fix($schema['items']);
1221
            }
1222 16
            if (!empty($schema['properties'])) {
1223 4
                $properties = [];
1224
                foreach ($schema['properties'] as $key => $property) {
1225 16
                    $properties[$key] = $fix($property);
1226 11
                }
1227 11
                $schema['properties'] = $properties;
1228 11
            }
1229
1230 11
            return $schema;
1231
        };
1232
1233 16
        $result = $fix($this->schema);
1234 16
1235
        return $result;
1236 16
    }
1237
1238 16
    /**
1239
     * Look up a type based on its alias.
1240
     *
1241
     * @param string $alias The type alias or type name to lookup.
1242
     * @return mixed
1243
     */
1244
    protected function getType($alias) {
1245
        if (isset(self::$types[$alias])) {
1246
            return $alias;
1247 134
        }
1248 134
        foreach (self::$types as $type => $aliases) {
1249
            if (in_array($alias, $aliases, true)) {
1250
                return $type;
1251 134
            }
1252 134
        }
1253 134
        return null;
1254
    }
1255
1256 6
    /**
1257
     * Get the class that's used to contain validation information.
1258
     *
1259
     * @return Validation|string Returns the validation class.
1260
     */
1261
    public function getValidationClass() {
1262
        return $this->validationClass;
1263
    }
1264 145
1265 145
    /**
1266
     * Set the class that's used to contain validation information.
1267
     *
1268
     * @param Validation|string $class Either the name of a class or a class that will be cloned.
1269
     * @return $this
1270
     */
1271
    public function setValidationClass($class) {
1272
        if (!is_a($class, Validation::class, true)) {
1273
            throw new \InvalidArgumentException("$class must be a subclass of ".Validation::class, 500);
1274 1
        }
1275 1
1276
        $this->validationClass = $class;
1277
        return $this;
1278
    }
1279 1
1280 1
    /**
1281
     * Create a new validation instance.
1282
     *
1283
     * @return Validation Returns a validation object.
1284
     */
1285
    protected function createValidation() {
1286
        $class = $this->getValidationClass();
1287
1288 145
        if ($class instanceof Validation) {
1289 145
            $result = clone $class;
1290
        } else {
1291 145
            $result = new $class;
1292 1
        }
1293
        return $result;
1294 145
    }
1295
1296 145
    /**
1297
     * Check whether or not a value is an array or accessible like an array.
1298
     *
1299
     * @param mixed $value The value to check.
1300
     * @return bool Returns **true** if the value can be used like an array or **false** otherwise.
1301
     */
1302
    private function isArray($value) {
1303
        return is_array($value) || ($value instanceof \ArrayAccess && $value instanceof \Traversable);
1304
    }
1305 83
1306 83
    /**
1307
     * Cast a value to an array.
1308
     *
1309
     * @param \Traversable $value The value to convert.
1310
     * @return array Returns an array.
1311
     */
1312
    private function toObjectArray(\Traversable $value) {
1313
        $class = get_class($value);
1314
        if ($value instanceof \ArrayObject) {
1315 3
            return new $class($value->getArrayCopy(), $value->getFlags(), $value->getIteratorClass());
1316 3
        } elseif ($value instanceof \ArrayAccess) {
1317 3
            $r = new $class;
1318 2
            foreach ($value as $k => $v) {
1319 1
                $r[$k] = $v;
1320 1
            }
1321 1
            return $r;
1322 1
        }
1323
        return iterator_to_array($value);
1324 1
    }
1325
1326
    /**
1327
     * Return a sparse version of this schema.
1328
     *
1329
     * A sparse schema has no required properties.
1330
     *
1331
     * @return Schema Returns a new sparse schema.
1332
     */
1333
    public function withSparse() {
1334
        $sparseSchema = $this->withSparseInternal($this, new \SplObjectStorage());
1335
        return $sparseSchema;
1336 2
    }
1337 2
1338 2
    /**
1339
     * The internal implementation of `Schema::withSparse()`.
1340
     *
1341
     * @param array|Schema $schema The schema to make sparse.
1342
     * @param \SplObjectStorage $schemas Collected sparse schemas that have already been made.
1343
     * @return mixed
1344
     */
1345
    private function withSparseInternal($schema, \SplObjectStorage $schemas) {
1346
        if ($schema instanceof Schema) {
1347
            if ($schemas->contains($schema)) {
1348 2
                return $schemas[$schema];
1349 2
            } else {
1350 2
                $schemas[$schema] = $sparseSchema = new Schema();
1351 1
                $sparseSchema->schema = $schema->withSparseInternal($schema->schema, $schemas);
1352
                if ($id = $sparseSchema->getID()) {
1353 2
                    $sparseSchema->setID($id.'Sparse');
1354 2
                }
1355 2
1356
                return $sparseSchema;
1357
            }
1358
        }
1359 2
1360
        unset($schema['required']);
1361
1362
        if (isset($schema['items'])) {
1363 2
            $schema['items'] = $this->withSparseInternal($schema['items'], $schemas);
1364
        }
1365 2
        if (isset($schema['properties'])) {
1366 1
            foreach ($schema['properties'] as $name => &$property) {
1367
                $property = $this->withSparseInternal($property, $schemas);
1368 2
            }
1369 2
        }
1370 2
1371
        return $schema;
1372
    }
1373
1374 2
    /**
1375
     * Filter a field's value using built in and custom filters.
1376
     *
1377
     * @param mixed $value The original value of the field.
1378
     * @param ValidationField $field The field information for the field.
1379
     * @return mixed Returns the filtered field or the original field value if there are no filters.
1380
     */
1381
    private function filterField($value, ValidationField $field) {
1382
        // Check for limited support for Open API style.
1383
        if (!empty($field->val('style')) && is_string($value)) {
1384 145
            $doFilter = true;
1385
            if ($field->hasType('boolean') && in_array($value, ['true', 'false', '0', '1'], true)) {
1386 145
                $doFilter = false;
1387 8
            } elseif ($field->hasType('integer') || $field->hasType('number') && is_numeric($value)) {
1388 8
                $doFilter = false;
1389 4
            }
1390 4
1391
            if ($doFilter) {
1392
                switch ($field->val('style')) {
1393
                    case 'form':
1394 8
                        $value = explode(',', $value);
1395 4
                        break;
1396 4
                    case 'spaceDelimited':
1397 2
                        $value = explode(' ', $value);
1398 2
                        break;
1399 2
                    case 'pipeDelimited':
1400 1
                        $value = explode('|', $value);
1401 1
                        break;
1402 1
                }
1403 1
            }
1404 1
        }
1405
1406
        $value = $this->callFilters($value, $field);
1407
1408
        return $value;
1409 145
    }
1410
1411 145
    /**
1412
     * Whether a offset exists.
1413
     *
1414
     * @param mixed $offset An offset to check for.
1415
     * @return boolean true on success or false on failure.
1416
     * @link http://php.net/manual/en/arrayaccess.offsetexists.php
1417
     */
1418
    public function offsetExists($offset) {
1419
        return isset($this->schema[$offset]);
1420
    }
1421 6
1422 6
    /**
1423
     * Offset to retrieve.
1424
     *
1425
     * @param mixed $offset The offset to retrieve.
1426
     * @return mixed Can return all value types.
1427
     * @link http://php.net/manual/en/arrayaccess.offsetget.php
1428
     */
1429
    public function offsetGet($offset) {
1430
        return isset($this->schema[$offset]) ? $this->schema[$offset] : null;
1431
    }
1432 2
1433 2
    /**
1434
     * Offset to set.
1435
     *
1436
     * @param mixed $offset The offset to assign the value to.
1437
     * @param mixed $value The value to set.
1438
     * @link http://php.net/manual/en/arrayaccess.offsetset.php
1439
     */
1440
    public function offsetSet($offset, $value) {
1441
        $this->schema[$offset] = $value;
1442
    }
1443 1
1444 1
    /**
1445 1
     * Offset to unset.
1446
     *
1447
     * @param mixed $offset The offset to unset.
1448
     * @link http://php.net/manual/en/arrayaccess.offsetunset.php
1449
     */
1450
    public function offsetUnset($offset) {
1451
        unset($this->schema[$offset]);
1452
    }
1453 1
1454 1
    /**
1455 1
     * Validate a field against a single type.
1456
     *
1457
     * @param mixed $value The value to validate.
1458
     * @param string $type The type to validate against.
1459
     * @param ValidationField $field Contains field and validation information.
1460
     * @param bool $sparse Whether or not this should be a sparse validation.
1461
     * @return mixed Returns the valid value or `Invalid`.
1462
     */
1463
    protected function validateSingleType($value, $type, ValidationField $field, $sparse) {
1464
        switch ($type) {
1465
            case 'boolean':
1466 144
                $result = $this->validateBoolean($value, $field);
1467
                break;
1468 144
            case 'integer':
1469 28
                $result = $this->validateInteger($value, $field);
1470 28
                break;
1471 125
            case 'number':
1472 35
                $result = $this->validateNumber($value, $field);
1473 35
                break;
1474 120
            case 'string':
1475 10
                $result = $this->validateString($value, $field);
1476 10
                break;
1477 116
            case 'timestamp':
1478 63
                $result = $this->validateTimestamp($value, $field);
1479 63
                break;
1480 96
            case 'datetime':
1481 5
                $result = $this->validateDatetime($value, $field);
1482 5
                break;
1483 96
            case 'array':
1484 7
                $result = $this->validateArray($value, $field, $sparse);
1485 7
                break;
1486 93
            case 'object':
1487 20
                $result = $this->validateObject($value, $field, $sparse);
1488 20
                break;
1489 84
            case 'null':
1490 83
                $result = $this->validateNull($value, $field);
1491 81
                break;
1492 3
            case null:
1493 1
                // No type was specified so we are valid.
1494 1
                $result = $value;
1495 2
                break;
1496
            default:
1497 2
                throw new \InvalidArgumentException("Unrecognized type $type.", 500);
1498 2
        }
1499
        return $result;
1500
    }
1501
1502 144
    /**
1503
     * Validate a field against multiple basic types.
1504
     *
1505
     * The first validation that passes will be returned. If no type can be validated against then validation will fail.
1506
     *
1507
     * @param mixed $value The value to validate.
1508
     * @param string[] $types The types to validate against.
1509
     * @param ValidationField $field Contains field and validation information.
1510
     * @param bool $sparse Whether or not this should be a sparse validation.
1511
     * @return mixed Returns the valid value or `Invalid`.
1512
     */
1513
    private function validateMultipleTypes($value, array $types, ValidationField $field, $sparse) {
1514
        // First check for an exact type match.
1515
        switch (gettype($value)) {
1516 24
            case 'boolean':
1517
                if (in_array('boolean', $types)) {
1518 24
                    $singleType = 'boolean';
1519 24
                }
1520 3
                break;
1521 3
            case 'integer':
1522
                if (in_array('integer', $types)) {
1523 3
                    $singleType = 'integer';
1524 21
                } elseif (in_array('number', $types)) {
1525 5
                    $singleType = 'number';
1526 4
                }
1527 1
                break;
1528 1
            case 'double':
1529
                if (in_array('number', $types)) {
1530 5
                    $singleType = 'number';
1531 16
                } elseif (in_array('integer', $types)) {
1532 3
                    $singleType = 'integer';
1533 3
                }
1534
                break;
1535
            case 'string':
1536
                if (in_array('datetime', $types) && preg_match(self::$DATE_REGEX, $value)) {
1537 3
                    $singleType = 'datetime';
1538 13
                } elseif (in_array('string', $types)) {
1539 10
                    $singleType = 'string';
1540 1
                }
1541 9
                break;
1542 5
            case 'array':
1543
                if (in_array('array', $types) && in_array('object', $types)) {
1544 10
                    $singleType = isset($value[0]) || empty($value) ? 'array' : 'object';
1545 3
                } elseif (in_array('object', $types)) {
1546 3
                    $singleType = 'object';
1547
                } elseif (in_array('array', $types)) {
1548 3
                    $singleType = 'array';
1549
                }
1550 3
                break;
1551 3
            case 'NULL':
1552
                if (in_array('null', $types)) {
1553 3
                    $singleType = $this->validateSingleType($value, 'null', $field, $sparse);
1554
                }
1555
                break;
1556
        }
1557
        if (!empty($singleType)) {
1558
            return $this->validateSingleType($value, $singleType, $field, $sparse);
1559
        }
1560 24
1561 20
        // Clone the validation field to collect errors.
1562
        $typeValidation = new ValidationField(new Validation(), $field->getField(), '', $sparse);
1563
1564
        // Try and validate against each type.
1565 4
        foreach ($types as $type) {
1566
            $result = $this->validateSingleType($value, $type, $typeValidation, $sparse);
1567
            if (Invalid::isValid($result)) {
1568 4
                return $result;
1569 4
            }
1570 4
        }
1571 4
1572
        // Since we got here the value is invalid.
1573
        $field->merge($typeValidation->getValidation());
1574
        return Invalid::value();
1575
    }
1576
}
1577