Created
September 13, 2017 15:28
-
-
Save chrisguitarguy/3d2770a28780f14163eac55d4492e057 to your computer and use it in GitHub Desktop.
This file contains 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 declare(strict_types=1); | |
/* | |
* This file is part of pmg/core | |
* | |
* Copyright (c) PMG <https://www.pmg.com>. | |
* | |
* For the full copyright and license information, please view the LICENSE | |
* file that was distributed with this source code. | |
*/ | |
namespace PMG\Core; | |
final class Json | |
{ | |
public static function decode(string $in) : array | |
{ | |
$out = \json_decode($in, true); | |
if (null === $out && self::hasJsonError()) { | |
throw Json\JsonDecodeError::fromLastError(); | |
} | |
return $out; | |
} | |
public static function encode($in, int $options=0) : string | |
{ | |
$out = \json_encode($in, $options); | |
if (false === $out) { | |
throw Json\JsonEncodeError::fromLastError(sprintf( | |
'Could not encode %s - ', | |
Types::of($in) | |
)); | |
} | |
return $out; | |
} | |
private static function hasJsonError() | |
{ | |
return \json_last_error() !== JSON_ERROR_NONE; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment