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

ZF-9577
- Zend_Json: Added html output format for json output


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

ralph 14 лет назад
Родитель
Сommit
5f974fcc6d
2 измененных файлов с 99 добавлено и 35 удалено
  1. 67 35
      library/Zend/Json.php
  2. 32 0
      tests/Zend/JsonTest.php

+ 67 - 35
library/Zend/Json.php

@@ -179,12 +179,15 @@ class Zend_Json
      * NOTE: This method is used internally by the encode method.
      *
      * @see encode
-     * @param mixed $valueToCheck a string - object property to be encoded
+     * @param array|object|Zend_Json_Expr $value a string - object property to be encoded
+     * @param array $javascriptExpressions
+     * @param null $currentKey
+     *
+     * @internal param mixed $valueToCheck
      * @return void
      */
-    protected static function _recursiveJsonExprFinder(
-        &$value, array &$javascriptExpressions, $currentKey = null
-    ) {
+    protected static function _recursiveJsonExprFinder(&$value, array &$javascriptExpressions, $currentKey = null)
+    {
          if ($value instanceof Zend_Json_Expr) {
             // TODO: Optimize with ascii keys, if performance is bad
             $magicKey = "____" . $currentKey . "_" . (count($javascriptExpressions));
@@ -206,6 +209,7 @@ class Zend_Json
         }
         return $value;
     }
+
     /**
      * Return the value of an XML attribute text or the text between
      * the XML tags
@@ -248,7 +252,8 @@ class Zend_Json
      * @param integer $recursionDepth
      * @return array
      */
-    protected static function _processXml ($simpleXmlElementObject, $ignoreXmlAttributes, $recursionDepth=0) {
+    protected static function _processXml($simpleXmlElementObject, $ignoreXmlAttributes, $recursionDepth=0)
+    {
         // Keep an eye on how deeply we are involved in recursion.
         if ($recursionDepth > self::$maxRecursionDepthAllowed) {
             // XML tree is too deep. Exit now by throwing an exception.
@@ -257,17 +262,19 @@ class Zend_Json
                 "Function _processXml exceeded the allowed recursion depth of " .
                 self::$maxRecursionDepthAllowed);
         } // End of if ($recursionDepth > self::$maxRecursionDepthAllowed)
-        $childrens= $simpleXmlElementObject->children();
-        $name= $simpleXmlElementObject->getName();
-        $value= self::_getXmlValue($simpleXmlElementObject);
-        $attributes= (array) $simpleXmlElementObject->attributes();
-        if (count($childrens)==0) {
+
+        $children = $simpleXmlElementObject->children();
+        $name = $simpleXmlElementObject->getName();
+        $value = self::_getXmlValue($simpleXmlElementObject);
+        $attributes = (array) $simpleXmlElementObject->attributes();
+
+        if (count($children) == 0) {
             if (!empty($attributes) && !$ignoreXmlAttributes) {
                 foreach ($attributes['@attributes'] as $k => $v) {
                     $attributes['@attributes'][$k]= self::_getXmlValue($v);
                 }
                 if (!empty($value)) {
-                    $attributes['@text']= $value;
+                    $attributes['@text'] = $value;
                 } 
                 return array($name => $attributes);
             } else {
@@ -275,31 +282,32 @@ class Zend_Json
             }
         } else {
             $childArray= array();
-            foreach ($childrens as $child) {
-                $childname= $child->getName();
-                $element= self::_processXml($child,$ignoreXmlAttributes,$recursionDepth+1);
+            foreach ($children as $child) {
+                $childname = $child->getName();
+                $element = self::_processXml($child,$ignoreXmlAttributes,$recursionDepth+1);
                 if (array_key_exists($childname, $childArray)) {
                     if (empty($subChild[$childname])) {
-                        $childArray[$childname]=array($childArray[$childname]);
-                        $subChild[$childname]=true;
+                        $childArray[$childname] = array($childArray[$childname]);
+                        $subChild[$childname] = true;
                     }
-                    $childArray[$childname][]= $element[$childname];
+                    $childArray[$childname][] = $element[$childname];
                 } else {
-                    $childArray[$childname]= $element[$childname];
+                    $childArray[$childname] = $element[$childname];
                 }
             }
             if (!empty($attributes) && !$ignoreXmlAttributes) {
                 foreach ($attributes['@attributes'] as $k => $v) {
-                    $attributes['@attributes'][$k]= self::_getXmlValue($v);
+                    $attributes['@attributes'][$k] = self::_getXmlValue($v);
                 }
-                $childArray['@attributes']= $attributes['@attributes'];
+                $childArray['@attributes'] = $attributes['@attributes'];
             }
             if (!empty($value)) {
-                $childArray['@text']= $value;
+                $childArray['@text'] = $value;
             }
             return array($name => $childArray);
         }
     }
+
     /**
      * fromXml - Converts XML to JSON
      *
@@ -326,7 +334,8 @@ class Zend_Json
      * @return mixed - JSON formatted string on success
      * @throws Zend_Json_Exception
      */
-    public static function fromXml ($xmlStringContents, $ignoreXmlAttributes=true) {
+    public static function fromXml($xmlStringContents, $ignoreXmlAttributes=true)
+    {
         // Load the XML formatted string into a Simple XML Element object.
         $simpleXmlElementObject = simplexml_load_string($xmlStringContents);
 
@@ -345,14 +354,15 @@ class Zend_Json
         // It is just that simple.
         $jsonStringOutput = self::encode($resultArray);
         return($jsonStringOutput);
-    } // End of function fromXml.
+    }
 
     
 
     /**
      * Pretty-print JSON string
      *
-     * Use 'indent' option to select indentation string - by default it's a tab
+     * Use 'format' option to select output format - currently html and txt supported, txt is default
+     * Use 'indent' option to override the indentation string set in the format - by default for the 'txt' format it's a tab
      *
      * @param string $json Original JSON string
      * @param array $options Encoding options
@@ -361,32 +371,54 @@ class Zend_Json
     public static function prettyPrint($json, $options = array())
     {
         $tokens = preg_split('|([\{\}\]\[,])|', $json, -1, PREG_SPLIT_DELIM_CAPTURE);
-        $result = "";
+        $result = '';
         $indent = 0;
 
+        $format= 'txt';
+
         $ind = "\t";
-        if(isset($options['indent'])) {
+
+        if (isset($options['format'])) {
+            $format = $options['format'];
+        }
+
+        switch ($format) {
+            case 'html':
+                $lineBreak = '<br />';
+                $ind = '&nbsp;&nbsp;&nbsp;&nbsp;';
+                break;
+            default:
+            case 'txt':
+                $lineBreak = "\n";
+                $ind = "\t";
+                break;
+        }
+
+        // override the defined indent setting with the supplied option
+        if (isset($options['indent'])) {
             $ind = $options['indent'];
         }
 
         foreach($tokens as $token) {
-            if($token == "") continue;
+            if($token == '') {
+                continue;
+            }
 
             $prefix = str_repeat($ind, $indent);
-            if($token == "{" || $token == "[") {
+            if ($token == '{' || $token == '[') {
                 $indent++;
-                if($result != "" && $result[strlen($result)-1] == "\n") {
+                if (($result != '') && ($result[(strlen($result)-1)] == $lineBreak)) {
                     $result .= $prefix;
                 }
-                $result .= "$token\n";
-            } else if($token == "}" || $token == "]") {
+                $result .= $token . $lineBreak;
+            } elseif ($token == '}' || $token == ']') {
                 $indent--;
                 $prefix = str_repeat($ind, $indent);
-                $result .= "\n$prefix$token";
-            } else if($token == ",") {
-                $result .= "$token\n";
+                $result .= $lineBreak . $prefix . $token;
+            } elseif ($token == ',') {
+                $result .= $token . $lineBreak;
             } else {
-                $result .= $prefix.$token;
+                $result .= $prefix . $token;
             }
         }
         return $result;

+ 32 - 0
tests/Zend/JsonTest.php

@@ -781,6 +781,38 @@ class Zend_JsonTest extends PHPUnit_Framework_TestCase
             $encoded
         );
     }
+
+    /**
+     * @group ZF-9577
+     */
+    public function testJsonPrettyPrintWorksWithTxtOutputFormat()
+    {
+        $o = new stdClass;
+        $o->four = 4;
+        $o->foo = array(1,2,3);
+
+        $jsonstr = Zend_Json::encode($o);
+
+        $targetTxtOutput = "{\n\t\"four\":4,\n\t\"foo\":[\n\t\t1,\n\t\t2,\n\t\t3\n\t]\n}";
+        $this->assertEquals($targetTxtOutput, Zend_Json::prettyPrint($jsonstr));
+    }
+
+    /**
+     * @group ZF-9577
+     */
+    public function testJsonPrettyPrintWorksWithHtmlOutputFormat()
+    {
+        $o = new stdClass;
+        $o->four = 4;
+        $o->foo = array(1,2,3);
+
+        $jsonstr = Zend_Json::encode($o);
+        $targetHtmlOutput = '{<br />&nbsp;&nbsp;&nbsp;&nbsp;"four":4,<br />&nbsp;&nbsp;&nbsp;&nbsp;"foo":[<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;3<br />&nbsp;&nbsp;&nbsp;&nbsp;]<br />}';
+        $this->assertEquals($targetHtmlOutput, Zend_Json::prettyPrint($jsonstr, array('format' => 'html')));
+    }
+
+
+
 }
 
 /**