2
0
Quellcode durchsuchen

ZF-11167
Zend_Json
Have Zend_Json::encode check for toArray() method on value to encode


git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@24419 44c647ce-9c0f-0410-b52a-842ac1e357ba

adamlundrigan vor 14 Jahren
Ursprung
Commit
528585bc55
2 geänderte Dateien mit 62 neuen und 2 gelöschten Zeilen
  1. 6 2
      library/Zend/Json.php
  2. 56 0
      tests/Zend/JsonTest.php

+ 6 - 2
library/Zend/Json.php

@@ -125,8 +125,12 @@ class Zend_Json
      */
     public static function encode($valueToEncode, $cycleCheck = false, $options = array())
     {
-        if (is_object($valueToEncode) && method_exists($valueToEncode, 'toJson')) {
-            return $valueToEncode->toJson();
+        if (is_object($valueToEncode)) {
+            if (method_exists($valueToEncode, 'toJson')) {
+                return $valueToEncode->toJson();
+            } elseif (method_exists($valueToEncode, 'toArray')) {
+                return self::encode($valueToEncode->toArray(), $cycleCheck, $options);
+            }
         }
 
         // Pre-encoding look for Zend_Json_Expr objects and replacing by tmp ids

+ 56 - 0
tests/Zend/JsonTest.php

@@ -811,7 +811,28 @@ class Zend_JsonTest extends PHPUnit_Framework_TestCase
         $this->assertEquals($targetHtmlOutput, Zend_Json::prettyPrint($jsonstr, array('format' => 'html')));
     }
 
+    /**
+     * @group ZF-11167
+     */
+    public function testEncodeWillUseToArrayMethodWhenAvailable()
+    {
+        $o = new ZF11167_ToArrayClass();
+        $objJson = Zend_Json::encode($o);
+        $arrJson = Zend_Json::encode($o->toArray());
+        $this->assertSame($arrJson, $objJson);
+    }
 
+    /**
+     * @group ZF-11167
+     */
+    public function testEncodeWillUseToJsonWhenBothToJsonAndToArrayMethodsAreAvailable()
+    {
+        $o = new ZF11167_ToArrayToJsonClass();
+        $objJson = Zend_Json::encode($o);
+        $this->assertEquals('"bogus"', $objJson);
+        $arrJson = Zend_Json::encode($o->toArray());
+        $this->assertNotSame($objJson, $arrJson);
+    }
 
 }
 
@@ -868,6 +889,41 @@ class ToJsonClass
 }
 
 /**
+ * Serializable class exposing a toArray() method
+ * @see ZF-11167
+ */
+class ZF11167_ToArrayClass
+{
+    private $_firstName = 'John';
+
+    private $_lastName = 'Doe';
+
+    private $_email = 'john@doe.com';
+
+    public function toArray()
+    {
+        $data = array(
+            'firstName' => $this->_firstName,
+            'lastName'  => $this->_lastName,
+            'email'     => $this->_email
+        );
+        return $data;
+    }
+}
+
+/**
+ * Serializable class exposing both toArray() and toJson() methods
+ * @see ZF-11167
+ */
+class ZF11167_ToArrayToJsonClass extends ZF11167_ToArrayClass
+{    
+    public function toJson()
+    {
+        return Zend_Json::encode('bogus');
+    }
+}
+
+/**
  * ISSUE  ZF-4946
  *
  */