Completed
Pull Request — master (#44)
by Todd
04:11
created

Schema::validateObject()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 8
nc 4
nop 2
dl 0
loc 11
ccs 9
cts 9
cp 1
crap 5
rs 9.6111
c 0
b 0
f 0
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 213
    public function __construct(array $schema = []) {
77 213
        $this->schema = $schema;
78 213
    }
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 1
    public function setDescription(string $description) {
96 1
        $this->schema['description'] = $description;
97 1
        return $this;
98
    }
99
100
    /**
101
     * Get a schema field.
102
     *
103
     * @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 5
    public function getField($path, $default = null) {
108 5
        if (is_string($path)) {
109 5
            $path = explode('.', $path);
110
        }
111
112 5
        $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 1
            } elseif ($value instanceof Schema) {
117 1
                return $value->getField(array_slice($path, $i), $default);
118
            } else {
119 5
                return $default;
120
            }
121
        }
122 5
        return $value;
123
    }
124
125
    /**
126
     * Set a schema field.
127
     *
128
     * @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 3
    public function setField($path, $value) {
133 3
        if (is_string($path)) {
134 3
            $path = explode('.', $path);
135
        }
136
137 3
        $selection = &$this->schema;
138 3
        foreach ($path as $i => $subSelector) {
139 3
            if (is_array($selection)) {
140 3
                if (!isset($selection[$subSelector])) {
141 3
                    $selection[$subSelector] = [];
142
                }
143 1
            } elseif ($selection instanceof Schema) {
144 1
                $selection->setField(array_slice($path, $i), $value);
145 1
                return $this;
146
            } else {
147
                $selection = [$subSelector => []];
148
            }
149 3
            $selection = &$selection[$subSelector];
150
        }
151
152 3
        $selection = $value;
153 3
        return $this;
154
    }
155
156
    /**
157
     * Get the ID for the schema.
158
     *
159
     * @return string
160
     */
161 3
    public function getID(): string {
162 3
        return isset($this->schema['id']) ? $this->schema['id'] : '';
163
    }
164
165
    /**
166
     * Set the ID for the schema.
167
     *
168
     * @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 1
    public function setID(string $id) {
173 1
        if (is_string($id)) {
0 ignored issues
show
introduced by
The condition is_string($id) is always true.
Loading history...
174 1
            $this->schema['id'] = $id;
175
        } else {
176
            throw new \InvalidArgumentException("The ID is not a valid string.", 500);
177
        }
178
179 1
        return $this;
180
    }
181
182
    /**
183
     * Return the validation flags.
184
     *
185
     * @return int Returns a bitwise combination of flags.
186
     */
187 1
    public function getFlags(): int {
188 1
        return $this->flags;
189
    }
190
191
    /**
192
     * Set the validation flags.
193
     *
194
     * @param int $flags One or more of the **Schema::FLAG_*** constants.
195
     * @return Schema Returns the current instance for fluent calls.
196
     */
197 7
    public function setFlags(int $flags) {
198 7
        if (!is_int($flags)) {
0 ignored issues
show
introduced by
The condition is_int($flags) is always true.
Loading history...
199
            throw new \InvalidArgumentException('Invalid flags.', 500);
200
        }
201 7
        $this->flags = $flags;
202
203 7
        return $this;
204
    }
205
206
    /**
207
     * Whether or not the schema has a flag (or combination of flags).
208
     *
209
     * @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 12
    public function hasFlag(int $flag): bool {
213 12
        return ($this->flags & $flag) === $flag;
214
    }
215
216
    /**
217
     * Set a flag.
218
     *
219
     * @param int $flag One or more of the **Schema::VALIDATE_*** constants.
220
     * @param bool $value Either true or false.
221
     * @return $this
222
     */
223 1
    public function setFlag(int $flag, bool $value) {
224 1
        if ($value) {
225 1
            $this->flags = $this->flags | $flag;
226
        } else {
227 1
            $this->flags = $this->flags & ~$flag;
228
        }
229 1
        return $this;
230
    }
231
232
    /**
233
     * Merge a schema with this one.
234
     *
235
     * @param Schema $schema A scheme instance. Its parameters will be merged into the current instance.
236
     * @return $this
237
     */
238 4
    public function merge(Schema $schema) {
239 4
        $this->mergeInternal($this->schema, $schema->getSchemaArray(), true, true);
240 4
        return $this;
241
    }
242
243
    /**
244
     * Add another schema to this one.
245
     *
246
     * 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 4
    public function add(Schema $schema, $addProperties = false) {
253 4
        $this->mergeInternal($this->schema, $schema->getSchemaArray(), false, $addProperties);
254 4
        return $this;
255
    }
256
257
    /**
258
     * The internal implementation of schema merging.
259
     *
260
     * @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 7
    private function mergeInternal(array &$target, array $source, $overwrite = true, $addProperties = true) {
267
        // We need to do a fix for required properties here.
268 7
        if (isset($target['properties']) && !empty($source['required'])) {
269 5
            $required = isset($target['required']) ? $target['required'] : [];
270
271 5
            if (isset($source['required']) && $addProperties) {
272 4
                $newProperties = array_diff(array_keys($source['properties']), array_keys($target['properties']));
273 4
                $newRequired = array_intersect($source['required'], $newProperties);
274
275 4
                $required = array_merge($required, $newRequired);
276
            }
277
        }
278
279
280 7
        foreach ($source as $key => $val) {
281 7
            if (is_array($val) && array_key_exists($key, $target) && is_array($target[$key])) {
282 7
                if ($key === 'properties' && !$addProperties) {
283
                    // We just want to merge the properties that exist in the destination.
284 2
                    foreach ($val as $name => $prop) {
285 2
                        if (isset($target[$key][$name])) {
286 2
                            $targetProp = &$target[$key][$name];
287
288 2
                            if (is_array($targetProp) && is_array($prop)) {
289 2
                                $this->mergeInternal($targetProp, $prop, $overwrite, $addProperties);
290 1
                            } elseif (is_array($targetProp) && $prop instanceof Schema) {
291
                                $this->mergeInternal($targetProp, $prop->getSchemaArray(), $overwrite, $addProperties);
292 1
                            } elseif ($overwrite) {
293 2
                                $targetProp = $prop;
294
                            }
295
                        }
296
                    }
297 7
                } elseif (isset($val[0]) || isset($target[$key][0])) {
298 5
                    if ($overwrite) {
299
                        // This is a numeric array, so just do a merge.
300 3
                        $merged = array_merge($target[$key], $val);
301 3
                        if (is_string($merged[0])) {
302 3
                            $merged = array_keys(array_flip($merged));
303
                        }
304 5
                        $target[$key] = $merged;
305
                    }
306
                } else {
307 7
                    $target[$key] = $this->mergeInternal($target[$key], $val, $overwrite, $addProperties);
308
                }
309 7
            } elseif (!$overwrite && array_key_exists($key, $target) && !is_array($val)) {
310
                // Do nothing, we aren't replacing.
311
            } else {
312 7
                $target[$key] = $val;
313
            }
314
        }
315
316 7
        if (isset($required)) {
317 5
            if (empty($required)) {
318 1
                unset($target['required']);
319
            } else {
320 5
                $target['required'] = $required;
321
            }
322
        }
323
324 7
        return $target;
325
    }
326
327
//    public function overlay(Schema $schema )
328
329
    /**
330
     * Returns the internal schema array.
331
     *
332
     * @return array
333
     * @see Schema::jsonSerialize()
334
     */
335 17
    public function getSchemaArray(): array {
336 17
        return $this->schema;
337
    }
338
339
    /**
340
     * Parse a short schema and return the associated schema.
341
     *
342
     * @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 173
    public static function parse(array $arr, ...$args) {
347 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

347
        $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...
348 173
        $schema->schema = $schema->parseInternal($arr);
349 172
        return $schema;
350
    }
351
352
    /**
353
     * Parse a schema in short form into a full schema array.
354
     *
355
     * @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 173
    protected function parseInternal(array $arr): array {
360 173
        if (empty($arr)) {
361
            // An empty schema validates to anything.
362 6
            return [];
363 168
        } elseif (isset($arr['type'])) {
364
            // This is a long form schema and can be parsed as the root.
365
            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
        } else {
367
            // Check for a root schema.
368 168
            $value = reset($arr);
369 168
            $key = key($arr);
370 168
            if (is_int($key)) {
371 105
                $key = $value;
372 105
                $value = null;
373
            }
374 168
            list ($name, $param) = $this->parseShortParam($key, $value);
375 167
            if (empty($name)) {
376 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...
377
            }
378
        }
379
380
        // If we are here then this is n object schema.
381 108
        list($properties, $required) = $this->parseProperties($arr);
382
383
        $result = [
384 108
            'type' => 'object',
385 108
            'properties' => $properties,
386 108
            'required' => $required
387
        ];
388
389 108
        return array_filter($result);
390
    }
391
392
    /**
393
     * Parse a schema node.
394
     *
395
     * @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 167
    private function parseNode($node, $value = null) {
400 167
        if (is_array($value)) {
401 59
            if (is_array($node['type'])) {
402
                trigger_error('Schemas with multiple types is deprecated.', E_USER_DEPRECATED);
403
            }
404
405
            // The value describes a bit more about the schema.
406 59
            switch ($node['type']) {
407 59
                case 'array':
408 11
                    if (isset($value['items'])) {
409
                        // The value includes array schema information.
410 4
                        $node = array_replace($node, $value);
411
                    } else {
412 7
                        $node['items'] = $this->parseInternal($value);
413
                    }
414 11
                    break;
415 49
                case 'object':
416
                    // The value is a schema of the object.
417 12
                    if (isset($value['properties'])) {
418
                        list($node['properties']) = $this->parseProperties($value['properties']);
419
                    } else {
420 12
                        list($node['properties'], $required) = $this->parseProperties($value);
421 12
                        if (!empty($required)) {
422 12
                            $node['required'] = $required;
423
                        }
424
                    }
425 12
                    break;
426
                default:
427 37
                    $node = array_replace($node, $value);
428 59
                    break;
429
            }
430 128
        } elseif (is_string($value)) {
431 101
            if ($node['type'] === 'array' && $arrType = $this->getType($value)) {
432 6
                $node['items'] = ['type' => $arrType];
433 97
            } elseif (!empty($value)) {
434 101
                $node['description'] = $value;
435
            }
436 32
        } elseif ($value === null) {
437
            // Parse child elements.
438 28
            if ($node['type'] === 'array' && isset($node['items'])) {
439
                // The value includes array schema information.
440
                $node['items'] = $this->parseInternal($node['items']);
441 28
            } elseif ($node['type'] === 'object' && isset($node['properties'])) {
442
                list($node['properties']) = $this->parseProperties($node['properties']);
443
444
            }
445
        }
446
447 167
        if (is_array($node)) {
448 166
            if (!empty($node['allowNull'])) {
449 1
                $node['nullable'] = true;
450
            }
451 166
            unset($node['allowNull']);
452
453 166
            if ($node['type'] === null || $node['type'] === []) {
454 4
                unset($node['type']);
455
            }
456
        }
457
458 167
        return $node;
459
    }
460
461
    /**
462
     * Parse the schema for an object's properties.
463
     *
464
     * @param array $arr An object property schema.
465
     * @return array Returns a schema array suitable to be placed in the **properties** key of a schema.
466
     */
467 108
    private function parseProperties(array $arr): array {
468 108
        $properties = [];
469 108
        $requiredProperties = [];
470 108
        foreach ($arr as $key => $value) {
471
            // Fix a schema specified as just a value.
472 108
            if (is_int($key)) {
473 81
                if (is_string($value)) {
474 81
                    $key = $value;
475 81
                    $value = '';
476
                } else {
477
                    throw new \InvalidArgumentException("Schema at position $key is not a valid parameter.", 500);
478
                }
479
            }
480
481
            // The parameter is defined in the key.
482 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

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

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

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