Skip to content

Instantly share code, notes, and snippets.

@chrisguitarguy
Created September 13, 2017 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisguitarguy/3d2770a28780f14163eac55d4492e057 to your computer and use it in GitHub Desktop.
Save chrisguitarguy/3d2770a28780f14163eac55d4492e057 to your computer and use it in GitHub Desktop.
<?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