Json: wrap json_encode to emit errors

refs #1445
This commit is contained in:
Thomas Gelf 2018-03-28 18:16:30 +02:00
parent 2f68489cac
commit 3e46602802
4 changed files with 84 additions and 1 deletions

View File

@ -0,0 +1,19 @@
<?php
namespace Icinga\Module\Director\Core;
use Icinga\Module\Director\Exception\JsonEncodeException;
class Json
{
public static function encode($string)
{
$result = json_encode($string);
if ($result === false) {
throw JsonEncodeException::forLastJsonError();
}
return $result;
}
}

View File

@ -141,7 +141,7 @@ class RestApiClient
}
if ($body !== null) {
$body = json_encode($body);
$body = Json::encode($body);
$headers[] = 'Content-Type: application/json';
}

View File

@ -0,0 +1,7 @@
<?php
namespace Icinga\Module\Director\Exception;
class JsonEncodeException extends JsonException
{
}

View File

@ -0,0 +1,57 @@
<?php
namespace Icinga\Module\Director\Exception;
use Icinga\Exception\IcingaException;
class JsonException extends IcingaException
{
public static function forLastJsonError($msg = null)
{
if ($msg === null) {
return new static(static::getJsonErrorMessage(json_last_error()));
} else {
$args = func_get_args();
$args[0] = $msg . ': ' . static::getJsonErrorMessage(json_last_error());
return call_user_func_array('static::__construct', $args);
}
}
public static function getJsonErrorMessage($code)
{
$map = [
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON',
JSON_ERROR_SYNTAX => 'Syntax error',
JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded'
];
if (array_key_exists($code, $map)) {
return $map[$code];
}
if (PHP_VERSION_ID >= 50500) {
$map = [
JSON_ERROR_RECURSION => 'One or more recursive references in the value to be encoded',
JSON_ERROR_INF_OR_NAN => 'One or more NAN or INF values in the value to be encoded',
JSON_ERROR_UNSUPPORTED_TYPE => 'A value of a type that cannot be encoded was given',
];
if (array_key_exists($code, $map)) {
return $map[$code];
}
}
if (PHP_VERSION_ID >= 70000) {
$map = [
JSON_ERROR_INVALID_PROPERTY_NAME => 'A property name that cannot be encoded was given',
JSON_ERROR_UTF16 => 'Malformed UTF-16 characters, possibly incorrectly encoded',
];
if (array_key_exists($code, $map)) {
return $map[$code];
}
}
return 'An error occured when parsing a JSON string';
}
}