Created
October 28, 2020 18:37
-
-
Save barnslig/f8de8bd0351e80c9081b75aba0ba0057 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Barnslig\Jmap\Core; | |
use Ds\Map; | |
use Ds\Vector; | |
/** | |
* JSON de-/encoder that throws on error and decodes into PHP Data Structures | |
*/ | |
final class JSON | |
{ | |
private static function mapToDs($obj) | |
{ | |
if ($obj instanceof \stdClass) { | |
return new Map(array_map("self::mapToDs", (array) $obj)); | |
} | |
if (is_array($obj)) { | |
return new Vector(array_map("self::mapToDs", $obj)); | |
} | |
return $obj; | |
} | |
/** | |
* Decodes a JSON string | |
* | |
* @see https://www.php.net/manual/en/function.json-decode.php | |
* @param string $json The json string being decoded. This function only works with UTF-8 encoded strings | |
* @param int $depth User specified recursion depth | |
* @param int $options Bitmask | |
* @throws JsonException | |
* @return mixed The value encoded in json in appropriate PHP type using Ds\Map and Ds\Vector for Arrays and Objects | |
*/ | |
public static function decode(string $json, int $depth = 512, int $options = 0) | |
{ | |
$data = json_decode($json, false, $depth, JSON_THROW_ON_ERROR | $options); | |
return self::mapToDs($data); | |
} | |
/** | |
* Encodes a value as JSON string | |
* | |
* @see https://www.php.net/manual/en/function.json-encode.php | |
* @param mixed $value The value being encoded | |
* @param int $options Bitmask | |
* @param int $depth Set the maximum depth. Must be greater than zero | |
* @throws JsonException | |
* @return string A JSON encoded string | |
*/ | |
public static function encode($json, int $options = 0, int $depth = 512): string | |
{ | |
return json_encode($json, JSON_THROW_ON_ERROR | $options, $depth); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment