Lines
14.28%
2 / 14
Methods
16.66%
1 / 6
Classes
0.00%
0 / 1
| Name | Lines | Methods | CRAP | ||||
|---|---|---|---|---|---|---|---|
| __construct | 0.00% | 0 / 1 | 0.00% | 0 / 1 | 2 | ||
| requireString | 100.00% | 2 / 2 | 100.00% | 1 / 1 | 2 | ||
| requireObjectList | 0.00% | 0 / 4 | 0.00% | 0 / 1 | 12 | ||
| requireObject | 0.00% | 0 / 4 | 0.00% | 0 / 1 | 6 | ||
| treatKeysAsStrings | 0.00% | 0 / 1 | 0.00% | 0 / 1 | 2 | ||
| requireList | 0.00% | 0 / 2 | 0.00% | 0 / 1 | 12 | ||
| 10 | final class JsonShape | |
| 11 | { | |
| 12 | private function __construct() {} | |
| 13 | ||
| 14 | /** @param array<array-key, mixed> $data */ | |
| 15 | public static function requireString(array $data, string $key): string | |
| 16 | { | |
| 17 | $value = $data[$key] ?? null; | |
| 18 | ||
| 19 | return \is_string($value) ? $value : throw JsonShapeException::wrongType($key, 'a string', get_debug_type($value)); | |
| 20 | } | |
| 21 | ||
| 22 | /** | |
| 23 | * @param array<array-key, mixed> $data | |
| 24 | * @return list<array<array-key, mixed>> | |
| 25 | */ | |
| 26 | public static function requireObjectList(array $data, string $key): array | |
| 27 | { | |
| 28 | $objects = []; | |
| 29 | ||
| 30 | foreach (self::requireList($data, $key) as $item) { | |
| 31 | $objects[] = \is_array($item) ? $item : throw JsonShapeException::wrongType($key, 'a list of objects', get_debug_type($item)); | |
| 32 | } | |
| 33 | ||
| 34 | return $objects; | |
| 35 | } | |
| 36 | ||
| 37 | /** | |
| 38 | * @param array<array-key, mixed> $data | |
| 39 | * @return array<string, mixed> | |
| 40 | */ | |
| 41 | public static function requireObject(array $data, string $key): array | |
| 42 | { | |
| 43 | $value = $data[$key] ?? null; | |
| 44 | ||
| 45 | if (!\is_array($value)) { | |
| 46 | throw JsonShapeException::wrongType($key, 'an object', get_debug_type($value)); | |
| 47 | } | |
| 48 | ||
| 49 | return self::treatKeysAsStrings($value); | |
| 50 | } | |
| 51 | ||
| 52 | /** | |
| 53 | * @param array<array-key, mixed> $raw | |
| 54 | * @return array<string, mixed> | |
| 55 | */ | |
| 56 | public static function treatKeysAsStrings(array $raw): array | |
| 57 | { | |
| 58 | // No copy: PHP converts numeric-string keys to int on write anyway. | |
| 59 | /** @var array<string, mixed> $raw */ | |
| 60 | return $raw; | |
| 61 | } | |
| 62 | ||
| 63 | /** | |
| 64 | * @param array<array-key, mixed> $data | |
| 65 | * @return list<mixed> | |
| 66 | */ | |
| 67 | private static function requireList(array $data, string $key): array | |
| 68 | { | |
| 69 | $value = $data[$key] ?? null; | |
| 70 | ||
| 71 | return \is_array($value) && array_is_list($value) ? $value : throw JsonShapeException::wrongType($key, 'a list', get_debug_type($value)); | |
| 72 | } | |
| 73 | } |