1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace League\JsonGuard\Constraints; |
4
|
|
|
|
5
|
|
|
use League\JsonGuard; |
6
|
|
|
use League\JsonGuard\Assert; |
7
|
|
|
use League\JsonGuard\ValidationError; |
8
|
|
|
use League\JsonGuard\Validator; |
9
|
|
|
|
10
|
|
|
class AdditionalItems implements Constraint |
11
|
|
|
{ |
12
|
|
|
const KEYWORD = 'additionalItems'; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* {@inheritdoc} |
16
|
|
|
*/ |
17
|
6 |
|
public function validate($value, $parameter, Validator $validator) |
18
|
|
|
{ |
19
|
6 |
|
Assert::type($parameter, ['boolean', 'object'], self::KEYWORD, $validator->getPointer()); |
20
|
|
|
|
21
|
4 |
|
if (!is_array($value) || $parameter === true) { |
22
|
4 |
|
return null; |
23
|
|
|
} |
24
|
|
|
|
25
|
4 |
|
if (!is_array($items = self::getItems($validator->getSchema()))) { |
26
|
4 |
|
return null; |
27
|
|
|
} |
28
|
|
|
|
29
|
4 |
|
if ($parameter === false) { |
30
|
4 |
|
return self::validateAdditionalItemsWhenNotAllowed($value, $items, $validator->getPointer()); |
31
|
4 |
|
} elseif (is_object($parameter)) { |
32
|
4 |
|
$additionalItems = array_slice($value, count($items)); |
33
|
|
|
|
34
|
4 |
|
return self::validateAdditionalItemsAgainstSchema($additionalItems, $parameter, $validator); |
35
|
|
|
} |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @param object $schema |
40
|
|
|
* |
41
|
|
|
* @return mixed |
42
|
|
|
*/ |
43
|
4 |
|
private static function getItems($schema) |
44
|
|
|
{ |
45
|
4 |
|
return property_exists($schema, 'items') ? $schema->items : null; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @param array $items |
50
|
|
|
* @param object $schema |
51
|
|
|
* @param Validator $validator |
52
|
|
|
* |
53
|
|
|
* @return array |
54
|
|
|
*/ |
55
|
4 |
|
private static function validateAdditionalItemsAgainstSchema($items, $schema, Validator $validator) |
56
|
|
|
{ |
57
|
4 |
|
$errors = []; |
58
|
4 |
|
foreach ($items as $key => $item) { |
59
|
|
|
// Escaping isn't necessary since the key is always numeric. |
60
|
4 |
|
$currentPointer = JsonGuard\pointer_push($validator->getPointer(), $key); |
61
|
4 |
|
$validator = $validator->makeSubSchemaValidator($item, $schema, $currentPointer); |
62
|
4 |
|
$errors = array_merge($errors, $validator->errors()); |
63
|
4 |
|
} |
64
|
|
|
|
65
|
4 |
|
return $errors; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @param array $value |
70
|
|
|
* @param array $items |
71
|
|
|
* @param $pointer |
72
|
|
|
* |
73
|
|
|
* @return \League\JsonGuard\ValidationError |
74
|
|
|
*/ |
75
|
4 |
|
private static function validateAdditionalItemsWhenNotAllowed($value, $items, $pointer) |
76
|
|
|
{ |
77
|
4 |
|
if (count($value) > count($items)) { |
78
|
4 |
|
return new ValidationError( |
79
|
4 |
|
'Additional items are not allowed.', |
80
|
4 |
|
self::KEYWORD, |
81
|
4 |
|
$value, |
82
|
|
|
$pointer |
83
|
4 |
|
); |
84
|
|
|
} |
85
|
4 |
|
} |
86
|
|
|
} |
87
|
|
|
|