-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidator.php
More file actions
405 lines (361 loc) · 14.6 KB
/
Validator.php
File metadata and controls
405 lines (361 loc) · 14.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
<?php
declare(strict_types=1);
namespace Maml\Schema;
use Maml\Ast\ArrayNode;
use Maml\Ast\BooleanNode;
use Maml\Ast\Document;
use Maml\Ast\FloatNode;
use Maml\Ast\IntegerNode;
use Maml\Ast\NullNode;
use Maml\Ast\ObjectNode;
use Maml\Ast\RawStringNode;
use Maml\Ast\Span;
use Maml\Ast\StringNode;
use Maml\Schema\Type\AnyType;
use Maml\Schema\Type\ArrayOfType;
use Maml\Schema\Type\BooleanType;
use Maml\Schema\Type\FloatType;
use Maml\Schema\Type\IntegerType;
use Maml\Schema\Type\LiteralType;
use Maml\Schema\Type\MapType;
use Maml\Schema\Type\NullType;
use Maml\Schema\Type\NumberType;
use Maml\Schema\Type\ObjectType;
use Maml\Schema\Type\OptionalType;
use Maml\Schema\Type\OrderedObjectType;
use Maml\Schema\Type\StringType;
use Maml\Schema\Type\TupleType;
use Maml\Schema\Type\UnionType;
final class Validator
{
/** @var ValidationError[] */
private array $errors = [];
/**
* @return ValidationError[]
*/
public static function validate(Document $doc, SchemaType $schema): array
{
$validator = new self();
$validator->validateNode($doc->value, $schema, '$');
return $validator->errors;
}
private function validateNode(
StringNode|RawStringNode|IntegerNode|FloatNode|BooleanNode|NullNode|ObjectNode|ArrayNode $node,
SchemaType $schema,
string $path,
): void {
// Unwrap OptionalType outside of object context
if ($schema instanceof OptionalType) {
$this->validateNode($node, $schema->inner, $path);
return;
}
if ($schema instanceof AnyType) {
return;
}
if ($schema instanceof StringType) {
if (!($node instanceof StringNode) && !($node instanceof RawStringNode)) {
$this->addError('Expected string, got ' . self::describeNode($node), $path, $node->span);
return;
}
if ($schema->pattern !== null && !\preg_match($schema->pattern, $node->value)) {
$this->addError(
'String does not match pattern ' . $schema->pattern,
$path,
$node->span,
);
}
return;
}
if ($schema instanceof IntegerType) {
if (!($node instanceof IntegerNode)) {
$this->addError('Expected integer, got ' . self::describeNode($node), $path, $node->span);
return;
}
$this->checkRange($node->value, $schema->min, $schema->max, $path, $node->span);
return;
}
if ($schema instanceof FloatType) {
if (!($node instanceof FloatNode)) {
$this->addError('Expected float, got ' . self::describeNode($node), $path, $node->span);
return;
}
$this->checkRange($node->value, $schema->min, $schema->max, $path, $node->span);
return;
}
if ($schema instanceof NumberType) {
if (!($node instanceof IntegerNode) && !($node instanceof FloatNode)) {
$this->addError('Expected number, got ' . self::describeNode($node), $path, $node->span);
return;
}
$this->checkRange($node->value, $schema->min, $schema->max, $path, $node->span);
return;
}
if ($schema instanceof BooleanType) {
if (!($node instanceof BooleanNode)) {
$this->addError('Expected boolean, got ' . self::describeNode($node), $path, $node->span);
}
return;
}
if ($schema instanceof NullType) {
if (!($node instanceof NullNode)) {
$this->addError('Expected null, got ' . self::describeNode($node), $path, $node->span);
}
return;
}
if ($schema instanceof LiteralType) {
$this->validateLiteral($node, $schema, $path);
return;
}
if ($schema instanceof ObjectType) {
$this->validateObject($node, $schema->properties, $schema->additionalProperties, $path);
return;
}
if ($schema instanceof OrderedObjectType) {
$this->validateObject($node, $schema->properties, $schema->additionalProperties, $path);
if ($node instanceof ObjectNode) {
$this->validateOrder($node, $schema->properties, $path);
}
return;
}
if ($schema instanceof MapType) {
if (!($node instanceof ObjectNode)) {
$this->addError('Expected ' . $schema->describe() . ', got ' . self::describeNode($node), $path, $node->span);
return;
}
foreach ($node->properties as $prop) {
$this->validateNode($prop->value, $schema->values, $path . '.' . $prop->key->value);
}
return;
}
if ($schema instanceof ArrayOfType) {
if (!($node instanceof ArrayNode)) {
$this->addError('Expected ' . $schema->describe() . ', got ' . self::describeNode($node), $path, $node->span);
return;
}
$count = \count($node->elements);
if ($schema->minItems !== null && $count < $schema->minItems) {
$this->addError(
'Expected at least ' . $schema->minItems . ' items, got ' . $count,
$path,
$node->span,
);
}
if ($schema->maxItems !== null && $count > $schema->maxItems) {
$this->addError(
'Expected at most ' . $schema->maxItems . ' items, got ' . $count,
$path,
$node->span,
);
}
foreach ($node->elements as $i => $element) {
$this->validateNode($element->value, $schema->items, $path . '[' . $i . ']');
}
return;
}
if ($schema instanceof TupleType) {
if (!($node instanceof ArrayNode)) {
$this->addError('Expected ' . $schema->describe() . ', got ' . self::describeNode($node), $path, $node->span);
return;
}
$expected = \count($schema->elements);
$actual = \count($node->elements);
if ($actual !== $expected) {
$this->addError(
'Expected array of length ' . $expected . ', got ' . $actual,
$path,
$node->span,
);
}
$len = \min($expected, $actual);
for ($i = 0; $i < $len; $i++) {
$this->validateNode($node->elements[$i]->value, $schema->elements[$i], $path . '[' . $i . ']');
}
return;
}
if ($schema instanceof UnionType) {
$this->validateUnion($node, $schema, $path);
return;
}
}
private function validateLiteral(
StringNode|RawStringNode|IntegerNode|FloatNode|BooleanNode|NullNode|ObjectNode|ArrayNode $node,
LiteralType $schema,
string $path,
): void {
$expected = $schema->value;
if ($expected === null) {
if (!($node instanceof NullNode)) {
$this->addError('Expected null, got ' . self::describeNode($node), $path, $node->span);
}
return;
}
if (\is_bool($expected)) {
if (!($node instanceof BooleanNode) || $node->value !== $expected) {
$this->addError('Expected ' . $schema->describe() . ', got ' . self::describeNodeValue($node), $path, $node->span);
}
return;
}
if (\is_string($expected)) {
if (($node instanceof StringNode || $node instanceof RawStringNode) && $node->value === $expected) {
return;
}
$this->addError('Expected ' . $schema->describe() . ', got ' . self::describeNodeValue($node), $path, $node->span);
return;
}
if (\is_int($expected)) {
if ($node instanceof IntegerNode && $node->value === $expected) {
return;
}
$this->addError('Expected ' . $schema->describe() . ', got ' . self::describeNodeValue($node), $path, $node->span);
return;
}
// float
if ($node instanceof FloatNode && $node->value === $expected) {
return;
}
$this->addError('Expected ' . $schema->describe() . ', got ' . self::describeNodeValue($node), $path, $node->span);
}
/**
* @param array<string, SchemaType> $properties
*/
private function validateObject(
StringNode|RawStringNode|IntegerNode|FloatNode|BooleanNode|NullNode|ObjectNode|ArrayNode $node,
array $properties,
?SchemaType $additionalProperties,
string $path,
): void {
if (!($node instanceof ObjectNode)) {
$desc = 'object{' . \implode(', ', \array_keys($properties)) . '}';
$this->addError('Expected ' . $desc . ', got ' . self::describeNode($node), $path, $node->span);
return;
}
// Build map of actual keys
$actual = [];
foreach ($node->properties as $prop) {
$actual[$prop->key->value] = $prop;
}
// Unknown keys: reject or validate against additionalProperties schema
foreach ($actual as $key => $prop) {
if (!isset($properties[$key])) {
if ($additionalProperties === null) {
$this->addError('Unknown property "' . $key . '"', $path . '.' . $key, $prop->key->span);
} else {
$this->validateNode($prop->value, $additionalProperties, $path . '.' . $key);
}
}
}
// Missing required keys + recurse into present values
foreach ($properties as $key => $propSchema) {
$isOptional = $propSchema instanceof OptionalType;
$innerSchema = $isOptional ? $propSchema->inner : $propSchema;
if (isset($actual[$key])) {
$this->validateNode($actual[$key]->value, $innerSchema, $path . '.' . $key);
} elseif (!$isOptional) {
$this->addError('Missing required property "' . $key . '"', $path . '.' . $key, $node->span);
}
}
}
/**
* @param array<string, SchemaType> $properties
*/
private function validateOrder(ObjectNode $node, array $properties, string $path): void
{
$schemaKeys = \array_keys($properties);
// Collect actual keys in AST order, filtered to schema-defined keys only
$actualOrder = [];
foreach ($node->properties as $prop) {
$key = $prop->key->value;
if (isset($properties[$key])) {
$actualOrder[] = $key;
}
}
// Expected order: schema keys filtered to only those present
$presentSet = \array_flip($actualOrder);
$expectedOrder = \array_filter($schemaKeys, fn(string $k) => isset($presentSet[$k]));
$expectedOrder = \array_values($expectedOrder);
if ($actualOrder !== $expectedOrder) {
$this->addError(
'Properties are not in the expected order. Expected: ' . \implode(', ', $expectedOrder),
$path,
$node->span,
);
}
}
private function validateUnion(
StringNode|RawStringNode|IntegerNode|FloatNode|BooleanNode|NullNode|ObjectNode|ArrayNode $node,
UnionType $schema,
string $path,
): void {
$bestErrors = null;
$bestDepth = -1;
$bestCount = \PHP_INT_MAX;
foreach ($schema->branches as $branch) {
$sub = new self();
$sub->validateNode($node, $branch, $path);
if ($sub->errors === []) {
return;
}
$maxDepth = 0;
foreach ($sub->errors as $e) {
$depth = \substr_count($e->path, '.') + \substr_count($e->path, '[');
$maxDepth = \max($maxDepth, $depth);
}
$count = \count($sub->errors);
if ($maxDepth > $bestDepth || ($maxDepth === $bestDepth && $count < $bestCount)) {
$bestErrors = $sub->errors;
$bestDepth = $maxDepth;
$bestCount = $count;
}
}
// If best branch matched deeper than the union's own path, report its specific errors
$unionDepth = \substr_count($path, '.') + \substr_count($path, '[');
if ($bestErrors !== null && $bestDepth > $unionDepth) {
\array_push($this->errors, ...$bestErrors);
} else {
$this->addError(
'Expected ' . $schema->describe() . ', got ' . self::describeNode($node),
$path,
$node->span,
);
}
}
private function checkRange(int|float $value, int|float|null $min, int|float|null $max, string $path, Span $span): void
{
if ($min !== null && $value < $min) {
$this->addError('Value ' . $value . ' is less than minimum ' . $min, $path, $span);
}
if ($max !== null && $value > $max) {
$this->addError('Value ' . $value . ' is greater than maximum ' . $max, $path, $span);
}
}
private function addError(string $message, string $path, ?Span $span): void
{
$this->errors[] = new ValidationError($message, $path, $span);
}
private static function describeNode(
StringNode|RawStringNode|IntegerNode|FloatNode|BooleanNode|NullNode|ObjectNode|ArrayNode $node,
): string {
return match (true) {
$node instanceof StringNode, $node instanceof RawStringNode => 'string',
$node instanceof IntegerNode => 'integer',
$node instanceof FloatNode => 'float',
$node instanceof BooleanNode => 'boolean',
$node instanceof NullNode => 'null',
$node instanceof ObjectNode => 'object',
$node instanceof ArrayNode => 'array',
};
}
private static function describeNodeValue(
StringNode|RawStringNode|IntegerNode|FloatNode|BooleanNode|NullNode|ObjectNode|ArrayNode $node,
): string {
return match (true) {
$node instanceof StringNode, $node instanceof RawStringNode => 'string "' . $node->value . '"',
$node instanceof IntegerNode => 'integer ' . $node->value,
$node instanceof FloatNode => 'float ' . $node->value,
$node instanceof BooleanNode => $node->value ? 'true' : 'false',
$node instanceof NullNode => 'null',
$node instanceof ObjectNode => 'object',
$node instanceof ArrayNode => 'array',
};
}
}