Completed
Pull Request — master (#45)
by Todd
05:46
created

Schema::validateField()   B

Complexity

Conditions 11
Paths 14

Size

Total Lines 31
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 11

Importance

Changes 0
Metric Value
cc 11
eloc 19
nc 14
nop 2
dl 0
loc 31
ccs 17
cts 17
cp 1
crap 11
rs 7.3166
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
37
        // Psuedo-types
38
        'timestamp' => ['ts'], // type: integer, format: timestamp
39
        'datetime' => ['dt'], // type: string, format: date-time
40
        'null' => ['n'], // Adds nullable: true
41
    ];
42
43
    /**
44
     * @var string The regular expression to strictly determine if a string is a date.
45
     */
46
    private static $DATE_REGEX = '`^\d{4}-\d{2}-\d{2}([ T]\d{2}:\d{2}(:\d{2})?)?`i';
47
48
    private $schema = [];
49
50
    /**
51
     * @var int A bitwise combination of the various **Schema::FLAG_*** constants.
52
     */
53
    private $flags = 0;
54
55
    /**
56
     * @var array An array of callbacks that will filter data in the schema.
57
     */
58
    private $filters = [];
59
60
    /**
61
     * @var array An array of callbacks that will custom validate the schema.
62
     */
63
    private $validators = [];
64
65
    /**
66
     * @var string|Validation The name of the class or an instance that will be cloned.
67
     */
68
    private $validationClass = Validation::class;
69
70
71
    /// Methods ///
72
73
    /**
74
     * Initialize an instance of a new {@link Schema} class.
75
     *
76
     * @param array $schema The array schema to validate against.
77
     */
78 213
    public function __construct(array $schema = []) {
79 213
        $this->schema = $schema;
80 213
    }
81
82
    /**
83
     * Grab the schema's current description.
84
     *
85
     * @return string
86
     */
87 1
    public function getDescription(): string {
88 1
        return $this->schema['description'] ?? '';
89
    }
90
91
    /**
92
     * Set the description for the schema.
93
     *
94
     * @param string $description The new description.
95
     * @return $this
96
     */
97 1
    public function setDescription(string $description) {
98 1
        $this->schema['description'] = $description;
99 1
        return $this;
100
    }
101
102
    /**
103
     * Get the schema's title.
104
     *
105
     * @return string Returns the title.
106
     */
107
    public function getTitle(): string {
108
        return $this->schema['title'] ?? '';
109
    }
110
111
    /**
112
     * Set the schema's title.
113
     *
114
     * @param string $title The new title.
115
     */
116
    public function setTitle(string $title) {
117
        $this->schema['title'] = $title;
118
    }
119
120
    /**
121
     * Get a schema field.
122
     *
123
     * @param string|array $path The JSON schema path of the field with parts separated by dots.
124
     * @param mixed $default The value to return if the field isn't found.
125
     * @return mixed Returns the field value or `$default`.
126
     */
127 5
    public function getField($path, $default = null) {
128 5
        if (is_string($path)) {
129 5
            $path = explode('.', $path);
130
        }
131
132 5
        $value = $this->schema;
133 5
        foreach ($path as $i => $subKey) {
134 5
            if (is_array($value) && isset($value[$subKey])) {
135 5
                $value = $value[$subKey];
136 1
            } elseif ($value instanceof Schema) {
137 1
                return $value->getField(array_slice($path, $i), $default);
138
            } else {
139 5
                return $default;
140
            }
141
        }
142 5
        return $value;
143
    }
144
145
    /**
146
     * Set a schema field.
147
     *
148
     * @param string|array $path The JSON schema path of the field with parts separated by dots.
149
     * @param mixed $value The new value.
150
     * @return $this
151
     */
152 3
    public function setField($path, $value) {
153 3
        if (is_string($path)) {
154 3
            $path = explode('.', $path);
155
        }
156
157 3
        $selection = &$this->schema;
158 3
        foreach ($path as $i => $subSelector) {
159 3
            if (is_array($selection)) {
160 3
                if (!isset($selection[$subSelector])) {
161 3
                    $selection[$subSelector] = [];
162
                }
163 1
            } elseif ($selection instanceof Schema) {
164 1
                $selection->setField(array_slice($path, $i), $value);
165 1
                return $this;
166
            } else {
167
                $selection = [$subSelector => []];
168
            }
169 3
            $selection = &$selection[$subSelector];
170
        }
171
172 3
        $selection = $value;
173 3
        return $this;
174
    }
175
176
    /**
177
     * Get the ID for the schema.
178
     *
179
     * @return string
180
     */
181 3
    public function getID(): string {
182 3
        return isset($this->schema['id']) ? $this->schema['id'] : '';
183
    }
184
185
    /**
186
     * Set the ID for the schema.
187
     *
188
     * @param string $id The new ID.
189
     * @throws \InvalidArgumentException Throws an exception when the provided ID is not a string.
190
     * @return Schema
191
     */
192 1
    public function setID(string $id) {
193 1
        if (is_string($id)) {
0 ignored issues
show
introduced by
The condition is_string($id) is always true.
Loading history...
194 1
            $this->schema['id'] = $id;
195
        } else {
196
            throw new \InvalidArgumentException("The ID is not a valid string.", 500);
197
        }
198
199 1
        return $this;
200
    }
201
202
    /**
203
     * Return the validation flags.
204
     *
205
     * @return int Returns a bitwise combination of flags.
206
     */
207 1
    public function getFlags(): int {
208 1
        return $this->flags;
209
    }
210
211
    /**
212
     * Set the validation flags.
213
     *
214
     * @param int $flags One or more of the **Schema::FLAG_*** constants.
215
     * @return Schema Returns the current instance for fluent calls.
216
     */
217 7
    public function setFlags(int $flags) {
218 7
        if (!is_int($flags)) {
0 ignored issues
show
introduced by
The condition is_int($flags) is always true.
Loading history...
219
            throw new \InvalidArgumentException('Invalid flags.', 500);
220
        }
221 7
        $this->flags = $flags;
222
223 7
        return $this;
224
    }
225
226
    /**
227
     * Whether or not the schema has a flag (or combination of flags).
228
     *
229
     * @param int $flag One or more of the **Schema::VALIDATE_*** constants.
230
     * @return bool Returns **true** if all of the flags are set or **false** otherwise.
231
     */
232 12
    public function hasFlag(int $flag): bool {
233 12
        return ($this->flags & $flag) === $flag;
234
    }
235
236
    /**
237
     * Set a flag.
238
     *
239
     * @param int $flag One or more of the **Schema::VALIDATE_*** constants.
240
     * @param bool $value Either true or false.
241
     * @return $this
242
     */
243 1
    public function setFlag(int $flag, bool $value) {
244 1
        if ($value) {
245 1
            $this->flags = $this->flags | $flag;
246
        } else {
247 1
            $this->flags = $this->flags & ~$flag;
248
        }
249 1
        return $this;
250
    }
251
252
    /**
253
     * Merge a schema with this one.
254
     *
255
     * @param Schema $schema A scheme instance. Its parameters will be merged into the current instance.
256
     * @return $this
257
     */
258 4
    public function merge(Schema $schema) {
259 4
        $this->mergeInternal($this->schema, $schema->getSchemaArray(), true, true);
260 4
        return $this;
261
    }
262
263
    /**
264
     * Add another schema to this one.
265
     *
266
     * Adding schemas together is analogous to array addition. When you add a schema it will only add missing information.
267
     *
268
     * @param Schema $schema The schema to add.
269
     * @param bool $addProperties Whether to add properties that don't exist in this schema.
270
     * @return $this
271
     */
272 4
    public function add(Schema $schema, $addProperties = false) {
273 4
        $this->mergeInternal($this->schema, $schema->getSchemaArray(), false, $addProperties);
274 4
        return $this;
275
    }
276
277
    /**
278
     * The internal implementation of schema merging.
279
     *
280
     * @param array &$target The target of the merge.
281
     * @param array $source The source of the merge.
282
     * @param bool $overwrite Whether or not to replace values.
283
     * @param bool $addProperties Whether or not to add object properties to the target.
284
     * @return array
285
     */
286 7
    private function mergeInternal(array &$target, array $source, $overwrite = true, $addProperties = true) {
287
        // We need to do a fix for required properties here.
288 7
        if (isset($target['properties']) && !empty($source['required'])) {
289 5
            $required = isset($target['required']) ? $target['required'] : [];
290
291 5
            if (isset($source['required']) && $addProperties) {
292 4
                $newProperties = array_diff(array_keys($source['properties']), array_keys($target['properties']));
293 4
                $newRequired = array_intersect($source['required'], $newProperties);
294
295 4
                $required = array_merge($required, $newRequired);
296
            }
297
        }
298
299
300 7
        foreach ($source as $key => $val) {
301 7
            if (is_array($val) && array_key_exists($key, $target) && is_array($target[$key])) {
302 7
                if ($key === 'properties' && !$addProperties) {
303
                    // We just want to merge the properties that exist in the destination.
304 2
                    foreach ($val as $name => $prop) {
305 2
                        if (isset($target[$key][$name])) {
306 2
                            $targetProp = &$target[$key][$name];
307
308 2
                            if (is_array($targetProp) && is_array($prop)) {
309 2
                                $this->mergeInternal($targetProp, $prop, $overwrite, $addProperties);
310 1
                            } elseif (is_array($targetProp) && $prop instanceof Schema) {
311
                                $this->mergeInternal($targetProp, $prop->getSchemaArray(), $overwrite, $addProperties);
312 1
                            } elseif ($overwrite) {
313 2
                                $targetProp = $prop;
314
                            }
315
                        }
316
                    }
317 7
                } elseif (isset($val[0]) || isset($target[$key][0])) {
318 5
                    if ($overwrite) {
319
                        // This is a numeric array, so just do a merge.
320 3
                        $merged = array_merge($target[$key], $val);
321 3
                        if (is_string($merged[0])) {
322 3
                            $merged = array_keys(array_flip($merged));
323
                        }
324 5
                        $target[$key] = $merged;
325
                    }
326
                } else {
327 7
                    $target[$key] = $this->mergeInternal($target[$key], $val, $overwrite, $addProperties);
328
                }
329 7
            } elseif (!$overwrite && array_key_exists($key, $target) && !is_array($val)) {
330
                // Do nothing, we aren't replacing.
331
            } else {
332 7
                $target[$key] = $val;
333
            }
334
        }
335
336 7
        if (isset($required)) {
337 5
            if (empty($required)) {
338 1
                unset($target['required']);
339
            } else {
340 5
                $target['required'] = $required;
341
            }
342
        }
343
344 7
        return $target;
345
    }
346
347
//    public function overlay(Schema $schema )
348
349
    /**
350
     * Returns the internal schema array.
351
     *
352
     * @return array
353
     * @see Schema::jsonSerialize()
354
     */
355 17
    public function getSchemaArray(): array {
356 17
        return $this->schema;
357
    }
358
359
    /**
360
     * Parse a short schema and return the associated schema.
361
     *
362
     * @param array $arr The schema array.
363
     * @param mixed[] $args Constructor arguments for the schema instance.
364
     * @return static Returns a new schema.
365
     */
366 173
    public static function parse(array $arr, ...$args) {
367 173
        $schema = new static([], ...$args);
0 ignored issues
show
Unused Code introduced by
The call to Garden\Schema\Schema::__construct() has too many arguments starting with $args. ( Ignorable by Annotation )

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

367
        $schema = /** @scrutinizer ignore-call */ new static([], ...$args);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
368 173
        $schema->schema = $schema->parseInternal($arr);
369 172
        return $schema;
370
    }
371
372
    /**
373
     * Parse a schema in short form into a full schema array.
374
     *
375
     * @param array $arr The array to parse into a schema.
376
     * @return array The full schema array.
377
     * @throws \InvalidArgumentException Throws an exception when an item in the schema is invalid.
378
     */
379 173
    protected function parseInternal(array $arr): array {
380 173
        if (empty($arr)) {
381
            // An empty schema validates to anything.
382 6
            return [];
383 168
        } elseif (isset($arr['type'])) {
384
            // This is a long form schema and can be parsed as the root.
385
            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...
386
        } else {
387
            // Check for a root schema.
388 168
            $value = reset($arr);
389 168
            $key = key($arr);
390 168
            if (is_int($key)) {
391 105
                $key = $value;
392 105
                $value = null;
393
            }
394 168
            list ($name, $param) = $this->parseShortParam($key, $value);
395 167
            if (empty($name)) {
396 62
                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...
397
            }
398
        }
399
400
        // If we are here then this is n object schema.
401 108
        list($properties, $required) = $this->parseProperties($arr);
402
403
        $result = [
404 108
            'type' => 'object',
405 108
            'properties' => $properties,
406 108
            'required' => $required
407
        ];
408
409 108
        return array_filter($result);
410
    }
411
412
    /**
413
     * Parse a schema node.
414
     *
415
     * @param array $node The node to parse.
416
     * @param mixed $value Additional information from the node.
417
     * @return array|\ArrayAccess Returns a JSON schema compatible node.
418
     */
419 167
    private function parseNode($node, $value = null) {
420 167
        if (is_array($value)) {
421 64
            if (is_array($node['type'])) {
422
                trigger_error('Schemas with multiple types is deprecated.', E_USER_DEPRECATED);
423
            }
424
425
            // The value describes a bit more about the schema.
426 64
            switch ($node['type']) {
427 64
                case 'array':
428 11
                    if (isset($value['items'])) {
429
                        // The value includes array schema information.
430 4
                        $node = array_replace($node, $value);
431
                    } else {
432 7
                        $node['items'] = $this->parseInternal($value);
433
                    }
434 11
                    break;
435 54
                case 'object':
436
                    // The value is a schema of the object.
437 12
                    if (isset($value['properties'])) {
438
                        list($node['properties']) = $this->parseProperties($value['properties']);
439
                    } else {
440 12
                        list($node['properties'], $required) = $this->parseProperties($value);
441 12
                        if (!empty($required)) {
442 12
                            $node['required'] = $required;
443
                        }
444
                    }
445 12
                    break;
446
                default:
447 42
                    $node = array_replace($node, $value);
448 64
                    break;
449
            }
450 128
        } elseif (is_string($value)) {
451 101
            if ($node['type'] === 'array' && $arrType = $this->getType($value)) {
452 6
                $node['items'] = ['type' => $arrType];
453 97
            } elseif (!empty($value)) {
454 101
                $node['description'] = $value;
455
            }
456 32
        } elseif ($value === null) {
457
            // Parse child elements.
458 28
            if ($node['type'] === 'array' && isset($node['items'])) {
459
                // The value includes array schema information.
460
                $node['items'] = $this->parseInternal($node['items']);
461 28
            } elseif ($node['type'] === 'object' && isset($node['properties'])) {
462
                list($node['properties']) = $this->parseProperties($node['properties']);
463
464
            }
465
        }
466
467 167
        if (is_array($node)) {
468 166
            if (!empty($node['allowNull'])) {
469 1
                $node['nullable'] = true;
470
            }
471 166
            unset($node['allowNull']);
472
473 166
            if ($node['type'] === null || $node['type'] === []) {
474 4
                unset($node['type']);
475
            }
476
        }
477
478 167
        return $node;
479
    }
480
481
    /**
482
     * Parse the schema for an object's properties.
483
     *
484
     * @param array $arr An object property schema.
485
     * @return array Returns a schema array suitable to be placed in the **properties** key of a schema.
486
     */
487 108
    private function parseProperties(array $arr): array {
488 108
        $properties = [];
489 108
        $requiredProperties = [];
490 108
        foreach ($arr as $key => $value) {
491
            // Fix a schema specified as just a value.
492 108
            if (is_int($key)) {
493 81
                if (is_string($value)) {
494 81
                    $key = $value;
495 81
                    $value = '';
496
                } else {
497
                    throw new \InvalidArgumentException("Schema at position $key is not a valid parameter.", 500);
498
                }
499
            }
500
501
            // The parameter is defined in the key.
502 108
            list($name, $param, $required) = $this->parseShortParam($key, $value);
0 ignored issues
show
Bug introduced by
$value of type string is incompatible with the type array expected by parameter $value of Garden\Schema\Schema::parseShortParam(). ( Ignorable by Annotation )

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

502
            list($name, $param, $required) = $this->parseShortParam($key, /** @scrutinizer ignore-type */ $value);
Loading history...
503
504 108
            $node = $this->parseNode($param, $value);
505
506 108
            $properties[$name] = $node;
507 108
            if ($required) {
508 108
                $requiredProperties[] = $name;
509
            }
510
        }
511 108
        return [$properties, $requiredProperties];
512
    }
513
514
    /**
515
     * Parse a short parameter string into a full array parameter.
516
     *
517
     * @param string $key The short parameter string to parse.
518
     * @param array $value An array of other information that might help resolve ambiguity.
519
     * @return array Returns an array in the form `[string name, array param, bool required]`.
520
     * @throws \InvalidArgumentException Throws an exception if the short param is not in the correct format.
521
     */
522 168
    public function parseShortParam(string $key, $value = []): array {
523
        // Is the parameter optional?
524 168
        if (substr($key, -1) === '?') {
525 70
            $required = false;
526 70
            $key = substr($key, 0, -1);
527
        } else {
528 120
            $required = true;
529
        }
530
531
        // Check for a type.
532 168
        $parts = explode(':', $key);
533 168
        $name = $parts[0];
534 168
        $types = [];
535 168
        $param = [];
536
537 168
        if (!empty($parts[1])) {
538 163
            $shortTypes = explode('|', $parts[1]);
539 163
            foreach ($shortTypes as $alias) {
540 163
                $found = $this->getType($alias);
541 163
                if ($found === null) {
542
                    throw new \InvalidArgumentException("Unknown type '$alias'", 500);
543 163
                } elseif ($found === 'datetime') {
544 9
                    $param['format'] = 'date-time';
545 9
                    $types[] = 'string';
546 155
                } elseif ($found === 'timestamp') {
547 12
                    $param['format'] = 'timestamp';
548 12
                    $types[] = 'integer';
549 149
                } elseif ($found === 'null') {
550 11
                    $nullable = true;
551
                } else {
552 163
                    $types[] = $found;
553
                }
554
            }
555
        }
556
557 168
        if ($value instanceof Schema) {
0 ignored issues
show
introduced by
$value is never a sub-type of Garden\Schema\Schema.
Loading history...
558 5
            if (count($types) === 1 && $types[0] === 'array') {
559 1
                $param += ['type' => $types[0], 'items' => $value];
560
            } else {
561 5
                $param = $value;
562
            }
563 167
        } elseif (isset($value['type'])) {
564 8
            $param = $value + $param;
565
566 8
            if (!empty($types) && $types !== (array)$param['type']) {
567
                $typesStr = implode('|', $types);
568
                $paramTypesStr = implode('|', (array)$param['type']);
569
570 8
                throw new \InvalidArgumentException("Type mismatch between $typesStr and {$paramTypesStr} for field $name.", 500);
571
            }
572
        } else {
573 164
            if (empty($types) && !empty($parts[1])) {
574
                throw new \InvalidArgumentException("Invalid type {$parts[1]} for field $name.", 500);
575
            }
576 164
            if (empty($types)) {
577 4
                $param += ['type' => null];
578
            } else {
579 163
                $param += ['type' => count($types) === 1 ? $types[0] : $types];
580
            }
581
582
            // Parsed required strings have a minimum length of 1.
583 164
            if (in_array('string', $types) && !empty($name) && $required && (!isset($value['default']) || $value['default'] !== '')) {
584 41
                $param['minLength'] = 1;
585
            }
586
        }
587
588 168
        if (!empty($nullable)) {
589 11
            $param['nullable'] = true;
590
        }
591
592 168
        if (is_array($param['type'])) {
593 1
            trigger_error('Schemas with multiple types is deprecated.', E_USER_DEPRECATED);
594
        }
595
596 167
        return [$name, $param, $required];
597
    }
598
599
    /**
600
     * Add a custom filter to change data before validation.
601
     *
602
     * @param string $fieldname The name of the field to filter, if any.
603
     *
604
     * If you are adding a filter to a deeply nested field then separate the path with dots.
605
     * @param callable $callback The callback to filter the field.
606
     * @return $this
607
     */
608 1
    public function addFilter(string $fieldname, callable $callback) {
609 1
        $this->filters[$fieldname][] = $callback;
610 1
        return $this;
611
    }
612
613
    /**
614
     * Add a custom validator to to validate the schema.
615
     *
616
     * @param string $fieldname The name of the field to validate, if any.
617
     *
618
     * If you are adding a validator to a deeply nested field then separate the path with dots.
619
     * @param callable $callback The callback to validate with.
620
     * @return Schema Returns `$this` for fluent calls.
621
     */
622 4
    public function addValidator(string $fieldname, callable $callback) {
623 4
        $this->validators[$fieldname][] = $callback;
624 4
        return $this;
625
    }
626
627
    /**
628
     * Require one of a given set of fields in the schema.
629
     *
630
     * @param array $required The field names to require.
631
     * @param string $fieldname The name of the field to attach to.
632
     * @param int $count The count of required items.
633
     * @return Schema Returns `$this` for fluent calls.
634
     */
635 3
    public function requireOneOf(array $required, string $fieldname = '', int $count = 1) {
636 3
        $result = $this->addValidator(
637 3
            $fieldname,
638 3
            function ($data, ValidationField $field) use ($required, $count) {
639
                // This validator does not apply to sparse validation.
640 3
                if ($field->isSparse()) {
641 1
                    return true;
642
                }
643
644 2
                $hasCount = 0;
645 2
                $flattened = [];
646
647 2
                foreach ($required as $name) {
648 2
                    $flattened = array_merge($flattened, (array)$name);
649
650 2
                    if (is_array($name)) {
651
                        // This is an array of required names. They all must match.
652 1
                        $hasCountInner = 0;
653 1
                        foreach ($name as $nameInner) {
654 1
                            if (array_key_exists($nameInner, $data)) {
655 1
                                $hasCountInner++;
656
                            } else {
657 1
                                break;
658
                            }
659
                        }
660 1
                        if ($hasCountInner >= count($name)) {
661 1
                            $hasCount++;
662
                        }
663 2
                    } elseif (array_key_exists($name, $data)) {
664 1
                        $hasCount++;
665
                    }
666
667 2
                    if ($hasCount >= $count) {
668 2
                        return true;
669
                    }
670
                }
671
672 2
                if ($count === 1) {
673 1
                    $message = 'One of {required} are required.';
674
                } else {
675 1
                    $message = '{count} of {required} are required.';
676
                }
677
678 2
                $field->addError('missingField', [
679 2
                    'messageCode' => $message,
680 2
                    'required' => $required,
681 2
                    'count' => $count
682
                ]);
683 2
                return false;
684 3
            }
685
        );
686
687 3
        return $result;
688
    }
689
690
    /**
691
     * Validate data against the schema.
692
     *
693
     * @param mixed $data The data to validate.
694
     * @param array $options Validation options.
695
     *
696
     * - **sparse**: Whether or not this is a sparse validation.
697
     * @return mixed Returns a cleaned version of the data.
698
     * @throws ValidationException Throws an exception when the data does not validate against the schema.
699
     */
700 173
    public function validate($data, $options = []) {
701 173
        if (is_bool($options)) {
0 ignored issues
show
introduced by
The condition is_bool($options) is always false.
Loading history...
702 1
            trigger_error("The $options parameter is deprecated. Use ['sparse' => true] instead.'", E_USER_DEPRECATED);
703 1
            $options = ['sparse' => true];
704
        }
705 173
        $options += ['sparse' => false];
706
707
708 173
        $field = new ValidationField($this->createValidation(), $this->schema, '', $options);
709
710 173
        $clean = $this->validateField($data, $field);
711
712 171
        if (Invalid::isInvalid($clean) && $field->isValid()) {
713
            // This really shouldn't happen, but we want to protect against seeing the invalid object.
714
            $field->addError('invalid', ['messageCode' => '{field} is invalid.', 'status' => 422]);
715
        }
716
717 171
        if (!$field->getValidation()->isValid()) {
718 60
            throw new ValidationException($field->getValidation());
719
        }
720
721 124
        return $clean;
722
    }
723
724
    /**
725
     * Validate data against the schema and return the result.
726
     *
727
     * @param mixed $data The data to validate.
728
     * @param array $options Validation options. See `Schema::validate()`.
729
     * @return bool Returns true if the data is valid. False otherwise.
730
     */
731 35
    public function isValid($data, $options = []) {
732
        try {
733 35
            $this->validate($data, $options);
734 25
            return true;
735 18
        } catch (ValidationException $ex) {
736 18
            return false;
737
        }
738
    }
739
740
    /**
741
     * Validate a field.
742
     *
743
     * @param mixed $value The value to validate.
744
     * @param ValidationField $field A validation object to add errors to.
745
     * @return mixed|Invalid Returns a clean version of the value with all extra fields stripped out or invalid if the value
746
     * is completely invalid.
747
     */
748 173
    protected function validateField($value, ValidationField $field) {
749 173
        $result = $value = $this->filterField($value, $field);
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
750
751 173
        if ($field->getField() instanceof Schema) {
752
            try {
753 5
                $result = $field->getField()->validate($value, $field->getOptions());
754 2
            } catch (ValidationException $ex) {
755
                // The validation failed, so merge the validations together.
756 5
                $field->getValidation()->merge($ex->getValidation(), $field->getName());
757
            }
758 173
        } elseif (($value === null || ($value === '' && !$field->hasType('string'))) && ($field->val('nullable') || $field->hasType('null'))) {
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: ($value === null || $val...$field->hasType('null'), Probably Intended Meaning: $value === null || ($val...field->hasType('null'))
Loading history...
759 13
            $result = null;
760
        } else {
761
            // Validate the field's type.
762 173
            $type = $field->getType();
763 173
            if (is_array($type)) {
764 29
                $result = $this->validateMultipleTypes($value, $type, $field);
765
            } else {
766 152
                $result = $this->validateSingleType($value, $type, $field);
767
            }
768 173
            if (Invalid::isValid($result)) {
769 171
                $result = $this->validateEnum($result, $field);
770
            }
771
        }
772
773
        // Validate a custom field validator.
774 173
        if (Invalid::isValid($result)) {
775 171
            $this->callValidators($result, $field);
776
        }
777
778 173
        return $result;
779
    }
780
781
    /**
782
     * Validate an array.
783
     *
784
     * @param mixed $value The value to validate.
785
     * @param ValidationField $field The validation results to add.
786
     * @return array|Invalid Returns an array or invalid if validation fails.
787
     */
788 29
    protected function validateArray($value, ValidationField $field) {
789 29
        if ((!is_array($value) || (count($value) > 0 && !array_key_exists(0, $value))) && !$value instanceof \Traversable) {
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: (! is_array($value) || c... instanceof Traversable, Probably Intended Meaning: ! is_array($value) || (c...instanceof Traversable)
Loading history...
790 6
            $field->addTypeError('array');
791 6
            return Invalid::value();
792
        } else {
793 24
            if ((null !== $minItems = $field->val('minItems')) && count($value) < $minItems) {
0 ignored issues
show
Bug introduced by
It seems like $value can also be of type Traversable; however, parameter $var of count() does only seem to accept Countable|array, 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

793
            if ((null !== $minItems = $field->val('minItems')) && count(/** @scrutinizer ignore-type */ $value) < $minItems) {
Loading history...
794 1
                $field->addError(
795 1
                    'minItems',
796
                    [
797 1
                        'messageCode' => '{field} must contain at least {minItems} {minItems,plural,item}.',
798 1
                        'minItems' => $minItems,
799 1
                        'status' => 422
800
                    ]
801
                );
802
            }
803 24
            if ((null !== $maxItems = $field->val('maxItems')) && count($value) > $maxItems) {
804 1
                $field->addError(
805 1
                    'maxItems',
806
                    [
807 1
                        'messageCode' => '{field} must contain no more than {maxItems} {maxItems,plural,item}.',
808 1
                        'maxItems' => $maxItems,
809 1
                        'status' => 422
810
                    ]
811
                );
812
            }
813
814 24
            if ($field->val('items') !== null) {
815 19
                $result = [];
816
817
                // Validate each of the types.
818 19
                $itemValidation = new ValidationField(
819 19
                    $field->getValidation(),
820 19
                    $field->val('items'),
821 19
                    '',
822 19
                    $field->getOptions()
823
                );
824
825 19
                $count = 0;
826 19
                foreach ($value as $i => $item) {
827 19
                    $itemValidation->setName($field->getName()."[{$i}]");
828 19
                    $validItem = $this->validateField($item, $itemValidation);
829 19
                    if (Invalid::isValid($validItem)) {
830 19
                        $result[] = $validItem;
831
                    }
832 19
                    $count++;
833
                }
834
835 19
                return empty($result) && $count > 0 ? Invalid::value() : $result;
836
            } else {
837
                // Cast the items into a proper numeric array.
838 5
                $result = is_array($value) ? array_values($value) : iterator_to_array($value);
839 5
                return $result;
840
            }
841
        }
842
    }
843
844
    /**
845
     * Validate a boolean value.
846
     *
847
     * @param mixed $value The value to validate.
848
     * @param ValidationField $field The validation results to add.
849
     * @return bool|Invalid Returns the cleaned value or invalid if validation fails.
850
     */
851 30
    protected function validateBoolean($value, ValidationField $field) {
852 30
        $value = $value === null ? $value : filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
853 30
        if ($value === null) {
854 4
            $field->addTypeError('boolean');
855 4
            return Invalid::value();
856
        }
857
858 27
        return $value;
859
    }
860
861
    /**
862
     * Validate a date time.
863
     *
864
     * @param mixed $value The value to validate.
865
     * @param ValidationField $field The validation results to add.
866
     * @return \DateTimeInterface|Invalid Returns the cleaned value or **null** if it isn't valid.
867
     */
868 14
    protected function validateDatetime($value, ValidationField $field) {
869 14
        if ($value instanceof \DateTimeInterface) {
870
            // do nothing, we're good
871 11
        } elseif (is_string($value) && $value !== '' && !is_numeric($value)) {
872
            try {
873 7
                $dt = new \DateTimeImmutable($value);
874 6
                if ($dt) {
0 ignored issues
show
introduced by
$dt is of type DateTimeImmutable, thus it always evaluated to true.
Loading history...
875 6
                    $value = $dt;
876
                } else {
877 6
                    $value = null;
878
                }
879 1
            } catch (\Throwable $ex) {
880 7
                $value = Invalid::value();
881
            }
882 4
        } elseif (is_int($value) && $value > 0) {
883
            try {
884 1
                $value = new \DateTimeImmutable('@'.(string)round($value));
885
            } catch (\Throwable $ex) {
886 1
                $value = Invalid::value();
887
            }
888
        } else {
889 3
            $value = Invalid::value();
890
        }
891
892 14
        if (Invalid::isInvalid($value)) {
893 4
            $field->addTypeError('datetime');
894
        }
895 14
        return $value;
896
    }
897
898
    /**
899
     * Validate a float.
900
     *
901
     * @param mixed $value The value to validate.
902
     * @param ValidationField $field The validation results to add.
903
     * @return float|Invalid Returns a number or **null** if validation fails.
904
     */
905 13
    protected function validateNumber($value, ValidationField $field) {
906 13
        $result = filter_var($value, FILTER_VALIDATE_FLOAT);
907 13
        if ($result === false) {
908 4
            $field->addTypeError('number');
909 4
            return Invalid::value();
910
        }
911 9
        return $result;
912
    }
913
    /**
914
     * Validate and integer.
915
     *
916
     * @param mixed $value The value to validate.
917
     * @param ValidationField $field The validation results to add.
918
     * @return int|Invalid Returns the cleaned value or **null** if validation fails.
919
     */
920 43
    protected function validateInteger($value, ValidationField $field) {
921 43
        if ($field->val('format') === 'timestamp') {
922 7
            return $this->validateTimestamp($value, $field);
923
        }
924
925 38
        $result = filter_var($value, FILTER_VALIDATE_INT);
926
927 38
        if ($result === false) {
928 9
            $field->addTypeError('integer');
929 9
            return Invalid::value();
930
        }
931 33
        return $result;
932
    }
933
934
    /**
935
     * Validate an object.
936
     *
937
     * @param mixed $value The value to validate.
938
     * @param ValidationField $field The validation results to add.
939
     * @return object|Invalid Returns a clean object or **null** if validation fails.
940
     */
941 99
    protected function validateObject($value, ValidationField $field) {
942 99
        if (!$this->isArray($value) || isset($value[0])) {
943 6
            $field->addTypeError('object');
944 6
            return Invalid::value();
945 99
        } elseif (is_array($field->val('properties'))) {
946
            // Validate the data against the internal schema.
947 94
            $value = $this->validateProperties($value, $field);
948 5
        } elseif (!is_array($value)) {
949 3
            $value = $this->toObjectArray($value);
950
        }
951 97
        return $value;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $value returns the type array which is incompatible with the documented return type object|Garden\Schema\Invalid.
Loading history...
952
    }
953
954
    /**
955
     * Validate data against the schema and return the result.
956
     *
957
     * @param array|\Traversable&\ArrayAccess $data The data to validate.
958
     * @param ValidationField $field This argument will be filled with the validation result.
959
     * @return array|Invalid Returns a clean array with only the appropriate properties and the data coerced to proper types.
960
     * or invalid if there are no valid properties.
961
     */
962 94
    protected function validateProperties($data, ValidationField $field) {
963 94
        $properties = $field->val('properties', []);
964 94
        $required = array_flip($field->val('required', []));
965
966 94
        if (is_array($data)) {
0 ignored issues
show
introduced by
The condition is_array($data) is always false.
Loading history...
967 90
            $keys = array_keys($data);
968 90
            $clean = [];
969
        } else {
970 4
            $keys = array_keys(iterator_to_array($data));
0 ignored issues
show
Bug introduced by
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

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