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
| <?php
namespace App\Services;
class JsonSchemaValidator { public function validate($data, array $schema): array { $errors = []; $this->validateSchema($data, $schema, '', $errors);
return [ 'valid' => empty($errors), 'errors' => $errors, ]; }
protected function validateSchema($data, array $schema, string $path, array &$errors): void { $type = $schema['type'] ?? null;
if ($type === 'object') { $this->validateObject($data, $schema, $path, $errors); } elseif ($type === 'array') { $this->validateArray($data, $schema, $path, $errors); } else { $this->validateScalar($data, $schema, $path, $errors); } }
protected function validateObject($data, array $schema, string $path, array &$errors): void { if (!is_array($data) || !$this->isAssociative($data)) { $errors[] = ['path' => $path, 'message' => 'Expected object']; return; }
$required = $schema['required'] ?? []; $properties = $schema['properties'] ?? [];
foreach ($required as $field) { if (!array_key_exists($field, $data)) { $errors[] = [ 'path' => $path, 'message' => "Missing required field: {$field}", ]; } }
foreach ($properties as $field => $fieldSchema) { if (array_key_exists($field, $data)) { $fieldPath = $path ? "{$path}.{$field}" : $field; $this->validateSchema($data[$field], $fieldSchema, $fieldPath, $errors); } } }
protected function validateArray($data, array $schema, string $path, array &$errors): void { if (!is_array($data)) { $errors[] = ['path' => $path, 'message' => 'Expected array']; return; }
$items = $schema['items'] ?? [];
foreach ($data as $index => $item) { $itemPath = $path ? "{$path}[{$index}]" : "[{$index}]"; $this->validateSchema($item, $items, $itemPath, $errors); } }
protected function validateScalar($data, array $schema, string $path, array &$errors): void { $type = $schema['type'] ?? null;
$valid = match ($type) { 'string' => is_string($data), 'number' => is_numeric($data), 'integer' => is_int($data), 'boolean' => is_bool($data), 'null' => is_null($data), default => true, };
if (!$valid) { $errors[] = ['path' => $path, 'message' => "Expected type: {$type}"]; }
if (isset($schema['enum']) && !in_array($data, $schema['enum'])) { $errors[] = ['path' => $path, 'message' => 'Value not in allowed enum']; }
if (isset($schema['minLength']) && strlen($data) < $schema['minLength']) { $errors[] = ['path' => $path, 'message' => "Minimum length: {$schema['minLength']}"]; }
if (isset($schema['maxLength']) && strlen($data) > $schema['maxLength']) { $errors[] = ['path' => $path, 'message' => "Maximum length: {$schema['maxLength']}"]; } }
protected function isAssociative(array $array): bool { return array_keys($array) !== range(0, count($array) - 1); } }
|