Просмотр исходного кода

ZF-8918: throw exceptions when decoding invalid JSON strings

git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20615 44c647ce-9c0f-0410-b52a-842ac1e357ba
matthew 16 лет назад
Родитель
Сommit
d4c00b2381
2 измененных файлов с 33 добавлено и 1 удалено
  1. 25 1
      library/Zend/Json.php
  2. 8 0
      tests/Zend/JsonTest.php

+ 25 - 1
library/Zend/Json.php

@@ -71,8 +71,32 @@ class Zend_Json
      */
     public static function decode($encodedValue, $objectDecodeType = Zend_Json::TYPE_ARRAY)
     {
+        $encodedValue = (string) $encodedValue;
         if (function_exists('json_decode') && self::$useBuiltinEncoderDecoder !== true) {
-            return json_decode($encodedValue, $objectDecodeType);
+            $decode = json_decode($encodedValue, $objectDecodeType);
+
+            // php < 5.3
+            if (!function_exists('json_last_error')) {
+                if ($decode === $encodedValue) {
+                    require_once 'Zend/Json/Exception.php';
+                    throw new Zend_Json_Exception('Decoding failed');
+                }
+            // php >= 5.3
+            } elseif (($jsonLastErr = json_last_error()) != JSON_ERROR_NONE) {
+                require_once 'Zend/Json/Exception.php';
+                switch ($jsonLastErr) {
+                    case JSON_ERROR_DEPTH:
+                        throw new Zend_Json_Exception('Decoding failed: Maximum stack depth exceeded');
+                    case JSON_ERROR_CTRL_CHAR:
+                        throw new Zend_Json_Exception('Decoding failed: Unexpected control character found');
+                    case JSON_ERROR_SYNTAX:
+                        throw new Zend_Json_Exception('Decoding failed: Syntax error');
+                    default:
+                        throw new Zend_Json_Exception('Decoding failed');
+                }
+            }
+
+            return $decode;
         }
 
         require_once 'Zend/Json/Decoder.php';

+ 8 - 0
tests/Zend/JsonTest.php

@@ -747,6 +747,14 @@ class Zend_JsonTest extends PHPUnit_Framework_TestCase
         $this->assertEquals($target, Zend_Json::encode($source));
     }
     
+    /**
+     * @group ZF-8918
+     * @expectedException Zend_Json_Exception
+     */
+    public function testDecodingInvalidJsonShouldRaiseAnException()
+    {
+        Zend_Json::decode(' some string ');
+    }
 }
 
 /**