| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Jose\Component\Core\Util; |
| 6 | |
| 7 | use InvalidArgumentException; |
| 8 | use Throwable; |
| 9 | use const JSON_THROW_ON_ERROR; |
| 10 | use const JSON_UNESCAPED_SLASHES; |
| 11 | use const JSON_UNESCAPED_UNICODE; |
| 12 | |
| 13 | final class JsonConverter |
| 14 | { |
| 15 | public static function encode(mixed $payload): string |
| 16 | { |
| 17 | try { |
| 18 | return json_encode($payload, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); |
| 19 | } catch (Throwable $throwable) { |
| 20 | throw new InvalidArgumentException('Invalid content.', $throwable->getCode(), $throwable); |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | public static function decode(string $payload): mixed |
| 25 | { |
| 26 | try { |
| 27 | return json_decode( |
| 28 | $payload, |
| 29 | true, |
| 30 | 512, |
| 31 | JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE |
| 32 | ); |
| 33 | } catch (Throwable $throwable) { |
| 34 | throw new InvalidArgumentException('Unsupported input.', $throwable->getCode(), $throwable); |
| 35 | } |
| 36 | } |
| 37 | } |