| 1 |
<?php |
| 2 |
|
| 3 |
declare (strict_types=1); |
| 4 |
namespace WCPOS\Vendor\Sentry\Util; |
| 5 |
|
| 6 |
use WCPOS\Vendor\Sentry\Exception\JsonException; |
| 7 |
/** |
| 8 |
* This class provides some utility methods to encode/decode JSON data. |
| 9 |
* |
| 10 |
* @author Stefano Arlandini <[email protected]> |
| 11 |
* |
| 12 |
* @internal |
| 13 |
*/ |
| 14 |
final class JSON |
| 15 |
{ |
| 16 |
/** |
| 17 |
* Encodes the given data into JSON. |
| 18 |
* |
| 19 |
* @param mixed $data The data to encode |
| 20 |
* @param int $options Bitmask consisting of JSON_* constants |
| 21 |
* @param int $maxDepth The maximum depth allowed for serializing $data |
| 22 |
* |
| 23 |
* @throws JsonException If the encoding failed |
| 24 |
*/ |
| 25 |
public static function encode($data, int $options = 0, int $maxDepth = 512) : string |
| 26 |
{ |
| 27 |
if ($maxDepth < 1) { |
| 28 |
throw new \InvalidArgumentException('The $maxDepth argument must be an integer greater than 0.'); |
| 29 |
} |
| 30 |
$options |= \JSON_UNESCAPED_UNICODE | \JSON_INVALID_UTF8_SUBSTITUTE | \JSON_PARTIAL_OUTPUT_ON_ERROR; |
| 31 |
$encodedData = \json_encode($data, $options, $maxDepth); |
| 32 |
$allowedErrors = [\JSON_ERROR_NONE, \JSON_ERROR_RECURSION, \JSON_ERROR_INF_OR_NAN, \JSON_ERROR_UNSUPPORTED_TYPE]; |
| 33 |
if (\defined('WCPOS\\Vendor\\JSON_ERROR_NON_BACKED_ENUM')) { |
| 34 |
$allowedErrors[] = \WCPOS\Vendor\JSON_ERROR_NON_BACKED_ENUM; |
| 35 |
} |
| 36 |
$encounteredAnyError = \json_last_error() !== \JSON_ERROR_NONE; |
| 37 |
if ($encounteredAnyError && ($encodedData === 'null' || $encodedData === \false) || !\in_array(\json_last_error(), $allowedErrors, \true)) { |
| 38 |
throw new JsonException(\sprintf('Could not encode value into JSON format. Error was: "%s".', \json_last_error_msg())); |
| 39 |
} |
| 40 |
return $encodedData; |
| 41 |
} |
| 42 |
/** |
| 43 |
* Decodes the given data from JSON. |
| 44 |
* |
| 45 |
* @param string $data The data to decode |
| 46 |
* |
| 47 |
* @return mixed |
| 48 |
* |
| 49 |
* @throws JsonException If the decoding failed |
| 50 |
*/ |
| 51 |
public static function decode(string $data) |
| 52 |
{ |
| 53 |
$decodedData = \json_decode($data, \true); |
| 54 |
if (\json_last_error() !== \JSON_ERROR_NONE) { |
| 55 |
throw new JsonException(\sprintf('Could not decode value from JSON format. Error was: "%s".', \json_last_error_msg())); |
| 56 |
} |
| 57 |
return $decodedData; |
| 58 |
} |
| 59 |
} |
| 60 |
|