|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Illuminate\JsonSchema; |
| 4 | + |
| 5 | +use RuntimeException; |
| 6 | + |
| 7 | +class Serializer |
| 8 | +{ |
| 9 | + /** |
| 10 | + * The properties to ignore when serializing. |
| 11 | + * |
| 12 | + * @var array<int, string> |
| 13 | + */ |
| 14 | + protected static array $ignore = ['required']; |
| 15 | + |
| 16 | + /** |
| 17 | + * Serialize the given property to an array. |
| 18 | + * |
| 19 | + * @return array<string, mixed> |
| 20 | + */ |
| 21 | + public static function serialize(Types\Type $type): array |
| 22 | + { |
| 23 | + /** @var array<string, mixed> $attributes */ |
| 24 | + $attributes = (fn () => get_object_vars($type))->call($type); |
| 25 | + |
| 26 | + $attributes['type'] = match (get_class($type)) { |
| 27 | + Types\ArrayType::class => 'array', |
| 28 | + Types\BooleanType::class => 'boolean', |
| 29 | + Types\IntegerType::class => 'integer', |
| 30 | + Types\NumberType::class => 'number', |
| 31 | + Types\ObjectType::class => 'object', |
| 32 | + Types\StringType::class => 'string', |
| 33 | + default => throw new RuntimeException('Unsupported ['.get_class($type).'] type.'), |
| 34 | + }; |
| 35 | + |
| 36 | + $attributes = array_filter($attributes, static function (mixed $value, string $key) { |
| 37 | + if (in_array($key, static::$ignore, true)) { |
| 38 | + return false; |
| 39 | + } |
| 40 | + |
| 41 | + return $value !== null; |
| 42 | + }, ARRAY_FILTER_USE_BOTH); |
| 43 | + |
| 44 | + if ($type instanceof Types\ObjectType) { |
| 45 | + if (count($attributes['properties']) === 0) { |
| 46 | + unset($attributes['properties']); |
| 47 | + } else { |
| 48 | + $required = array_keys(array_filter( |
| 49 | + $attributes['properties'], |
| 50 | + static fn (Types\Type $property) => static::isRequired($property), |
| 51 | + )); |
| 52 | + |
| 53 | + if (count($required) > 0) { |
| 54 | + $attributes['required'] = $required; |
| 55 | + } |
| 56 | + |
| 57 | + $attributes['properties'] = array_map( |
| 58 | + static fn (Types\Type $property) => static::serialize($property), |
| 59 | + $attributes['properties'], |
| 60 | + ); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + if ($type instanceof Types\ArrayType) { |
| 65 | + if (isset($attributes['items']) && $attributes['items'] instanceof Types\Type) { |
| 66 | + $attributes['items'] = static::serialize($attributes['items']); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + return $attributes; |
| 71 | + } |
| 72 | + |
| 73 | + /** |
| 74 | + * Determine if the given type is required. |
| 75 | + */ |
| 76 | + protected static function isRequired(Types\Type $type): bool |
| 77 | + { |
| 78 | + $attributes = (fn () => get_object_vars($type))->call($type); |
| 79 | + |
| 80 | + return isset($attributes['required']) && $attributes['required'] === true; |
| 81 | + } |
| 82 | +} |
0 commit comments