Completed
Push — master ( 42d70b...a9a521 )
by Todd
03:11 queued 01:13
created

Schema::setField()   A

Complexity

Conditions 6
Paths 10

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6.0106

Importance

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

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

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