Json.php
33 lines
| 1 | <?php declare(strict_types = 1); |
| 2 | |
| 3 | namespace MailPoet\Automation\Engine\Utils; |
| 4 | |
| 5 | if (!defined('ABSPATH')) exit; |
| 6 | |
| 7 | |
| 8 | use MailPoet\Automation\Engine\Exceptions; |
| 9 | use MailPoet\Automation\Engine\Exceptions\InvalidStateException; |
| 10 | |
| 11 | class Json { |
| 12 | public static function encode(array $value): string { |
| 13 | $json = json_encode((object)$value, JSON_HEX_TAG | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION); |
| 14 | $error = json_last_error(); |
| 15 | if ($error || $json === false) { |
| 16 | throw new InvalidStateException(json_last_error_msg(), (string)$error); |
| 17 | } |
| 18 | return $json; |
| 19 | } |
| 20 | |
| 21 | public static function decode(string $json): array { |
| 22 | $value = json_decode($json, true); |
| 23 | $error = json_last_error(); |
| 24 | if ($error) { |
| 25 | throw new InvalidStateException(json_last_error_msg(), (string)$error); |
| 26 | } |
| 27 | if (!is_array($value)) { |
| 28 | throw Exceptions::jsonNotObject($json); |
| 29 | } |
| 30 | return $value; |
| 31 | } |
| 32 | } |
| 33 |