| 1 |
<?php |
| 2 |
namespace Averta\WordPress\Utility; |
| 3 |
|
| 4 |
|
| 5 |
class JSON |
| 6 |
{ |
| 7 |
/** |
| 8 |
* Detect is JSON |
| 9 |
* |
| 10 |
* @param $args |
| 11 |
* |
| 12 |
* @return bool |
| 13 |
*/ |
| 14 |
public static function isJson(...$args) |
| 15 |
{ |
| 16 |
if(is_array($args[0]) || is_object($args[0])) { |
| 17 |
return false; |
| 18 |
} |
| 19 |
|
| 20 |
if (trim($args[0]) === '') { |
| 21 |
return false; |
| 22 |
} |
| 23 |
|
| 24 |
json_decode(...$args); |
| 25 |
return (json_last_error() == JSON_ERROR_NONE); |
| 26 |
} |
| 27 |
|
| 28 |
/** |
| 29 |
* Remove extra white-spaces and tabs from json string |
| 30 |
* |
| 31 |
* @param string $json |
| 32 |
* |
| 33 |
* @return string |
| 34 |
*/ |
| 35 |
public static function normalize( $json ) |
| 36 |
{ |
| 37 |
if( ! is_string( $json ) ) { |
| 38 |
return $json; |
| 39 |
} |
| 40 |
|
| 41 |
if (trim( $json ) === '') { |
| 42 |
return ''; |
| 43 |
} |
| 44 |
|
| 45 |
$decoded = json_decode( $json ); |
| 46 |
return (json_last_error() == JSON_ERROR_NONE) ? wp_json_encode( $decoded ) : $json; |
| 47 |
} |
| 48 |
|
| 49 |
/** |
| 50 |
* Encode a variable into JSON, with some sanity checks. |
| 51 |
* |
| 52 |
* @param mixed $value The value being encoded. Can be any type except a resource. |
| 53 |
* All string data must be UTF-8 encoded. |
| 54 |
* @param int $flags Options to be passed to json_encode(). Default 0. |
| 55 |
* @param int $depth Set the maximum depth. Must be greater than zero. |
| 56 |
* |
| 57 |
* @return false|string |
| 58 |
*/ |
| 59 |
public static function encode( $value, $flags = 0, $depth = 512 ) |
| 60 |
{ |
| 61 |
return wp_json_encode( $value, $flags, $depth ); |
| 62 |
} |
| 63 |
|
| 64 |
/** |
| 65 |
* Takes a JSON encoded string and converts it into a PHP variable. |
| 66 |
* |
| 67 |
* @param string $json The json string being decoded. |
| 68 |
* @param bool|null $associative When true, JSON objects will be returned as associative arrays; when false, JSON objects will be returned as objects. |
| 69 |
* When null, JSON objects will be returned as associative arrays or objects depending on whether JSON_OBJECT_AS_ARRAY is set in the flags. |
| 70 |
* @param int $depth Maximum nesting depth of the structure being decoded. |
| 71 |
* @param int $flags Bitmask of JSON_BIGINT_AS_STRING, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_OBJECT_AS_ARRAY, JSON_THROW_ON_ERROR |
| 72 |
* |
| 73 |
* @return mixed |
| 74 |
*/ |
| 75 |
public static function decode( $json, $associative = null, $depth = 512, $flags = 0 ) |
| 76 |
{ |
| 77 |
return json_decode( $json, $associative, $depth, $flags ); |
| 78 |
} |
| 79 |
|
| 80 |
|
| 81 |
} |
| 82 |
|