From ebc8d314ae9ab7e42a2e0021fc1936755918cd34 Mon Sep 17 00:00:00 2001 From: Chris Minett <1084019+chrisminett@users.noreply.github.com> Date: Fri, 14 Feb 2025 06:59:34 +0000 Subject: [PATCH 1/2] Add exact JSON method return type --- src/JsonTrait.php | 5 +---- src/Service.php | 4 +--- 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/src/JsonTrait.php b/src/JsonTrait.php index c09f0f7..f869bcb 100644 --- a/src/JsonTrait.php +++ b/src/JsonTrait.php @@ -13,10 +13,7 @@ */ trait JsonTrait { - /** - * @return mixed - */ - private static function decodeJson(string $json) + private static function decodeJson(string $json): string|int|bool|\stdClass { $result = json_decode($json, false); $errorCode = json_last_error(); diff --git a/src/Service.php b/src/Service.php index c3fc856..3f300a5 100644 --- a/src/Service.php +++ b/src/Service.php @@ -25,10 +25,8 @@ public function __construct( /** * Call service method - * - * @return mixed */ - public function __call(string $name, array $params) + public function __call(string $name, array $params): string|int|bool|\stdClass { $data = [ 'method' => $name, From d23d4442a1e17c19ebbf88f68cefaeaacdec6d8a Mon Sep 17 00:00:00 2001 From: Chris Minett <1084019+chrisminett@users.noreply.github.com> Date: Fri, 14 Feb 2025 07:01:39 +0000 Subject: [PATCH 2/2] Use JSON exceptions --- src/JsonTrait.php | 44 ++++---------------------------------------- 1 file changed, 4 insertions(+), 40 deletions(-) diff --git a/src/JsonTrait.php b/src/JsonTrait.php index f869bcb..bf86e09 100644 --- a/src/JsonTrait.php +++ b/src/JsonTrait.php @@ -15,46 +15,10 @@ trait JsonTrait { private static function decodeJson(string $json): string|int|bool|\stdClass { - $result = json_decode($json, false); - $errorCode = json_last_error(); - - if ($errorCode === JSON_ERROR_NONE) { - return $result; - } - - // Generate error message - switch ($errorCode) { - case JSON_ERROR_DEPTH: - $error = 'Maximum stack depth exceeded'; - break; - case JSON_ERROR_STATE_MISMATCH: - $error = 'Invalid or malformed JSON'; - break; - case JSON_ERROR_CTRL_CHAR: - $error = 'Unexpected control character found'; - break; - case JSON_ERROR_SYNTAX: - $error = 'Syntax error'; - break; - case JSON_ERROR_UTF8: - $error = 'Malformed UTF-8 characters, possibly incorrectly encoded'; - break; - case JSON_ERROR_UTF16: - $error = 'Malformed UTF-16 characters, possibly incorrectly encoded'; - break; - default: - $error = 'Unknown error'; - // Find the const name - $constants = get_defined_constants(true); - foreach ($constants['json'] as $name => $value) { - if (!strncmp($name, 'JSON_ERROR_', 11) && $value === $errorCode) { - $error = $name; - break; - } - } - break; + try { + return json_decode($json, false, flags: JSON_THROW_ON_ERROR); + } catch (\JsonException $e) { + throw new Exception\UnexpectedValueException("Problem decoding JSON : {$e->getMessage()} : '{$json}'"); } - - throw new Exception\UnexpectedValueException("Problem decoding JSON : {$error} : '{$json}'"); } }