| 1 |
<?php |
| 2 |
|
| 3 |
namespace Safe; |
| 4 |
|
| 5 |
use Safe\Exceptions\JsonException; |
| 6 |
|
| 7 |
/** |
| 8 |
* Returns a string containing the JSON representation of the supplied |
| 9 |
* value. |
| 10 |
* |
| 11 |
* The encoding is affected by the supplied options |
| 12 |
* and additionally the encoding of float values depends on the value of |
| 13 |
* serialize_precision. |
| 14 |
* |
| 15 |
* @param mixed $value The value being encoded. Can be any type except |
| 16 |
* a resource. |
| 17 |
* |
| 18 |
* All string data must be UTF-8 encoded. |
| 19 |
* |
| 20 |
* PHP implements a superset of JSON as specified in the original |
| 21 |
* RFC 7159. |
| 22 |
* @param int $options Bitmask consisting of |
| 23 |
* JSON_FORCE_OBJECT, |
| 24 |
* JSON_HEX_QUOT, |
| 25 |
* JSON_HEX_TAG, |
| 26 |
* JSON_HEX_AMP, |
| 27 |
* JSON_HEX_APOS, |
| 28 |
* JSON_INVALID_UTF8_IGNORE, |
| 29 |
* JSON_INVALID_UTF8_SUBSTITUTE, |
| 30 |
* JSON_NUMERIC_CHECK, |
| 31 |
* JSON_PARTIAL_OUTPUT_ON_ERROR, |
| 32 |
* JSON_PRESERVE_ZERO_FRACTION, |
| 33 |
* JSON_PRETTY_PRINT, |
| 34 |
* JSON_UNESCAPED_LINE_TERMINATORS, |
| 35 |
* JSON_UNESCAPED_SLASHES, |
| 36 |
* JSON_UNESCAPED_UNICODE, |
| 37 |
* JSON_THROW_ON_ERROR. |
| 38 |
* The behaviour of these constants is described on the |
| 39 |
* JSON constants page. |
| 40 |
* @param int $depth Set the maximum depth. Must be greater than zero. |
| 41 |
* @return string Returns a JSON encoded string on success. |
| 42 |
* @throws JsonException |
| 43 |
* |
| 44 |
*/ |
| 45 |
function json_encode($value, int $options = 0, int $depth = 512): string |
| 46 |
{ |
| 47 |
error_clear_last(); |
| 48 |
$result = \json_encode($value, $options, $depth); |
| 49 |
if ($result === false) { |
| 50 |
throw JsonException::createFromPhpError(); |
| 51 |
} |
| 52 |
return $result; |
| 53 |
} |
| 54 |
|
| 55 |
|
| 56 |
/** |
| 57 |
* Returns the error string of the last json_encode or json_decode |
| 58 |
* call, which did not specify JSON_THROW_ON_ERROR. |
| 59 |
* |
| 60 |
* @return string Returns the error message on success, "No error" if no |
| 61 |
* error has occurred. |
| 62 |
* @throws JsonException |
| 63 |
* |
| 64 |
*/ |
| 65 |
function json_last_error_msg(): string |
| 66 |
{ |
| 67 |
error_clear_last(); |
| 68 |
$result = \json_last_error_msg(); |
| 69 |
if ($result === false) { |
| 70 |
throw JsonException::createFromPhpError(); |
| 71 |
} |
| 72 |
return $result; |
| 73 |
} |
| 74 |
|