Lines
100.00%
21 / 21
Methods
100.00%
3 / 3
Classes
100.00%
1 / 1
| Name | Lines | Methods | CRAP | ||||
|---|---|---|---|---|---|---|---|
| sortMapKeysRecursively | 100.00% | 6 / 6 | 100.00% | 1 / 1 | 4 | ||
| findUnencodablePath | 100.00% | 11 / 11 | 100.00% | 1 / 1 | 10 | ||
| encodeCanonically | 100.00% | 4 / 4 | 100.00% | 1 / 1 | 1 | ||
| 8 | final class TriggerJson | |
| 9 | { | |
| 10 | /** | |
| 11 | * @param array<array-key, mixed> $value | |
| 12 | * @return array<array-key, mixed> | |
| 13 | */ | |
| 14 | public static function sortMapKeysRecursively(array $value): array | |
| 15 | { | |
| 16 | if (!array_is_list($value)) { | |
| 17 | ksort($value, \SORT_STRING); | |
| 18 | } | |
| 19 | ||
| 20 | foreach ($value as $key => $item) { | |
| 21 | if (\is_array($item)) { | |
| 22 | $value[$key] = self::sortMapKeysRecursively($item); | |
| 23 | } | |
| 24 | } | |
| 25 | ||
| 26 | return $value; | |
| 27 | } | |
| 28 | ||
| 29 | public static function findUnencodablePath(mixed $value, string $path): ?string | |
| 30 | { | |
| 31 | if (\is_float($value)) { | |
| 32 | return is_finite($value) ? null : $path; | |
| 33 | } | |
| 34 | ||
| 35 | if (\is_string($value)) { | |
| 36 | return preg_match('//u', $value) === 1 ? null : $path; | |
| 37 | } | |
| 38 | ||
| 39 | if (!\is_array($value)) { | |
| 40 | return $value === null || \is_scalar($value) ? null : $path; | |
| 41 | } | |
| 42 | ||
| 43 | foreach ($value as $key => $item) { | |
| 44 | $found = self::findUnencodablePath($item, $path . '.' . $key); | |
| 45 | ||
| 46 | if ($found !== null) { | |
| 47 | return $found; | |
| 48 | } | |
| 49 | } | |
| 50 | ||
| 51 | return null; | |
| 52 | } | |
| 53 | ||
| 54 | /** @param array<array-key, mixed> $value */ | |
| 55 | public static function encodeCanonically(array $value): string | |
| 56 | { | |
| 57 | return json_encode( | |
| 58 | self::sortMapKeysRecursively($value), | |
| 59 | \JSON_THROW_ON_ERROR | \JSON_PRESERVE_ZERO_FRACTION | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE, | |
| 60 | ); | |
| 61 | } | |
| 62 | } |