From d9b5c884ba9fd6d8be111894c55bb7811dbe9b73 Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Thu, 5 Mar 2015 14:24:43 +0000 Subject: [PATCH] Detect and warn JSON encoding failures, refs #3786 --- src/Composer/Json/JsonFile.php | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/Composer/Json/JsonFile.php b/src/Composer/Json/JsonFile.php index 3375329c7..7fbc42392 100644 --- a/src/Composer/Json/JsonFile.php +++ b/src/Composer/Json/JsonFile.php @@ -184,6 +184,9 @@ class JsonFile { if (version_compare(PHP_VERSION, '5.4', '>=')) { $json = json_encode($data, $options); + if (false === $json) { + self::throwEncodeError(json_last_error()); + } // compact brackets to follow recent php versions if (PHP_VERSION_ID < 50428 || (PHP_VERSION_ID >= 50500 && PHP_VERSION_ID < 50512) || (defined('JSON_C_VERSION') && version_compare(phpversion('json'), '1.3.6', '<'))) { @@ -195,6 +198,9 @@ class JsonFile } $json = json_encode($data); + if (false === $json) { + self::throwEncodeError(json_last_error()); + } $prettyPrint = (bool) ($options & self::JSON_PRETTY_PRINT); $unescapeUnicode = (bool) ($options & self::JSON_UNESCAPED_UNICODE); @@ -209,6 +215,28 @@ class JsonFile return $result; } + private static function throwEncodeError($code) + { + switch ($code) { + case JSON_ERROR_DEPTH: + $msg = 'Maximum stack depth exceeded'; + break; + case JSON_ERROR_STATE_MISMATCH: + $msg = 'Underflow or the modes mismatch'; + break; + case JSON_ERROR_CTRL_CHAR: + $msg = 'Unexpected control character found'; + break; + case JSON_ERROR_UTF8: + $msg = 'Malformed UTF-8 characters, possibly incorrectly encoded'; + break; + default: + $msg = 'Unknown error'; + } + + throw new \RuntimeException('JSON encoding failed: '.$msg); + } + /** * Parses json string and returns hash. *