PageRenderTime 147ms CodeModel.GetById 70ms app.highlight 31ms RepoModel.GetById 40ms app.codeStats 0ms

/library/Zend/Json/Encoder.php

https://bitbucket.org/fabiancarlos/feature_seguimentos
PHP | 575 lines | 286 code | 77 blank | 212 comment | 39 complexity | 283d17f29067ee86a69fb81f9b8e5c30 MD5 | raw file
  1<?php
  2/**
  3 * Zend Framework
  4 *
  5 * LICENSE
  6 *
  7 * This source file is subject to the new BSD license that is bundled
  8 * with this package in the file LICENSE.txt.
  9 * It is also available through the world-wide-web at this URL:
 10 * http://framework.zend.com/license/new-bsd
 11 * If you did not receive a copy of the license and are unable to
 12 * obtain it through the world-wide-web, please send an email
 13 * to license@zend.com so we can send you a copy immediately.
 14 *
 15 * @category   Zend
 16 * @package    Zend_Json
 17 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 18 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 19 * @version    $Id: Encoder.php 24152 2011-06-24 15:23:19Z adamlundrigan $
 20 */
 21
 22/**
 23 * Encode PHP constructs to JSON
 24 *
 25 * @category   Zend
 26 * @package    Zend_Json
 27 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 28 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 29 */
 30class Zend_Json_Encoder
 31{
 32    /**
 33     * Whether or not to check for possible cycling
 34     *
 35     * @var boolean
 36     */
 37    protected $_cycleCheck;
 38
 39    /**
 40     * Additional options used during encoding
 41     *
 42     * @var array
 43     */
 44    protected $_options = array();
 45
 46    /**
 47     * Array of visited objects; used to prevent cycling.
 48     *
 49     * @var array
 50     */
 51    protected $_visited = array();
 52
 53    /**
 54     * Constructor
 55     *
 56     * @param boolean $cycleCheck Whether or not to check for recursion when encoding
 57     * @param array $options Additional options used during encoding
 58     * @return void
 59     */
 60    protected function __construct($cycleCheck = false, $options = array())
 61    {
 62        $this->_cycleCheck = $cycleCheck;
 63        $this->_options = $options;
 64    }
 65
 66    /**
 67     * Use the JSON encoding scheme for the value specified
 68     *
 69     * @param mixed $value The value to be encoded
 70     * @param boolean $cycleCheck Whether or not to check for possible object recursion when encoding
 71     * @param array $options Additional options used during encoding
 72     * @return string  The encoded value
 73     */
 74    public static function encode($value, $cycleCheck = false, $options = array())
 75    {
 76        $encoder = new self(($cycleCheck) ? true : false, $options);
 77
 78        return $encoder->_encodeValue($value);
 79    }
 80
 81    /**
 82     * Recursive driver which determines the type of value to be encoded
 83     * and then dispatches to the appropriate method. $values are either
 84     *    - objects (returns from {@link _encodeObject()})
 85     *    - arrays (returns from {@link _encodeArray()})
 86     *    - basic datums (e.g. numbers or strings) (returns from {@link _encodeDatum()})
 87     *
 88     * @param mixed $value The value to be encoded
 89     * @return string Encoded value
 90     */
 91    protected function _encodeValue(&$value)
 92    {
 93        if (is_object($value)) {
 94            return $this->_encodeObject($value);
 95        } else if (is_array($value)) {
 96            return $this->_encodeArray($value);
 97        }
 98
 99        return $this->_encodeDatum($value);
100    }
101
102
103
104    /**
105     * Encode an object to JSON by encoding each of the public properties
106     *
107     * A special property is added to the JSON object called '__className'
108     * that contains the name of the class of $value. This is used to decode
109     * the object on the client into a specific class.
110     *
111     * @param object $value
112     * @return string
113     * @throws Zend_Json_Exception If recursive checks are enabled and the object has been serialized previously
114     */
115    protected function _encodeObject(&$value)
116    {
117        if ($this->_cycleCheck) {
118            if ($this->_wasVisited($value)) {
119
120                if (isset($this->_options['silenceCyclicalExceptions'])
121                    && $this->_options['silenceCyclicalExceptions']===true) {
122
123                    return '"* RECURSION (' . get_class($value) . ') *"';
124
125                } else {
126                    require_once 'Zend/Json/Exception.php';
127                    throw new Zend_Json_Exception(
128                        'Cycles not supported in JSON encoding, cycle introduced by '
129                        . 'class "' . get_class($value) . '"'
130                    );
131                }
132            }
133
134            $this->_visited[] = $value;
135        }
136
137        $props = '';
138
139        if ($value instanceof Iterator) {
140            $propCollection = $value;
141        } else {
142            $propCollection = get_object_vars($value);
143        }
144
145        foreach ($propCollection as $name => $propValue) {
146            if (isset($propValue)) {
147                $props .= ','
148                        . $this->_encodeString($name)
149                        . ':'
150                        . $this->_encodeValue($propValue);
151            }
152        }
153
154        $className = get_class($value);
155        return '{"__className":' . $this->_encodeString($className)
156                . $props . '}';
157    }
158
159
160    /**
161     * Determine if an object has been serialized already
162     *
163     * @param mixed $value
164     * @return boolean
165     */
166    protected function _wasVisited(&$value)
167    {
168        if (in_array($value, $this->_visited, true)) {
169            return true;
170        }
171
172        return false;
173    }
174
175
176    /**
177     * JSON encode an array value
178     *
179     * Recursively encodes each value of an array and returns a JSON encoded
180     * array string.
181     *
182     * Arrays are defined as integer-indexed arrays starting at index 0, where
183     * the last index is (count($array) -1); any deviation from that is
184     * considered an associative array, and will be encoded as such.
185     *
186     * @param array& $array
187     * @return string
188     */
189    protected function _encodeArray(&$array)
190    {
191        $tmpArray = array();
192
193        // Check for associative array
194        if (!empty($array) && (array_keys($array) !== range(0, count($array) - 1))) {
195            // Associative array
196            $result = '{';
197            foreach ($array as $key => $value) {
198                $key = (string) $key;
199                $tmpArray[] = $this->_encodeString($key)
200                            . ':'
201                            . $this->_encodeValue($value);
202            }
203            $result .= implode(',', $tmpArray);
204            $result .= '}';
205        } else {
206            // Indexed array
207            $result = '[';
208            $length = count($array);
209            for ($i = 0; $i < $length; $i++) {
210                $tmpArray[] = $this->_encodeValue($array[$i]);
211            }
212            $result .= implode(',', $tmpArray);
213            $result .= ']';
214        }
215
216        return $result;
217    }
218
219
220    /**
221     * JSON encode a basic data type (string, number, boolean, null)
222     *
223     * If value type is not a string, number, boolean, or null, the string
224     * 'null' is returned.
225     *
226     * @param mixed& $value
227     * @return string
228     */
229    protected function _encodeDatum(&$value)
230    {
231        $result = 'null';
232
233        if (is_int($value) || is_float($value)) {
234            $result = (string) $value;
235            $result = str_replace(",", ".", $result);
236        } elseif (is_string($value)) {
237            $result = $this->_encodeString($value);
238        } elseif (is_bool($value)) {
239            $result = $value ? 'true' : 'false';
240        }
241
242        return $result;
243    }
244
245
246    /**
247     * JSON encode a string value by escaping characters as necessary
248     *
249     * @param string& $value
250     * @return string
251     */
252    protected function _encodeString(&$string)
253    {
254        // Escape these characters with a backslash:
255        // " \ / \n \r \t \b \f
256        $search  = array('\\', "\n", "\t", "\r", "\b", "\f", '"', '/');
257        $replace = array('\\\\', '\\n', '\\t', '\\r', '\\b', '\\f', '\"', '\\/');
258        $string  = str_replace($search, $replace, $string);
259
260        // Escape certain ASCII characters:
261        // 0x08 => \b
262        // 0x0c => \f
263        $string = str_replace(array(chr(0x08), chr(0x0C)), array('\b', '\f'), $string);
264        $string = self::encodeUnicodeString($string);
265
266        return '"' . $string . '"';
267    }
268
269
270    /**
271     * Encode the constants associated with the ReflectionClass
272     * parameter. The encoding format is based on the class2 format
273     *
274     * @param ReflectionClass $cls
275     * @return string Encoded constant block in class2 format
276     */
277    private static function _encodeConstants(ReflectionClass $cls)
278    {
279        $result    = "constants : {";
280        $constants = $cls->getConstants();
281
282        $tmpArray = array();
283        if (!empty($constants)) {
284            foreach ($constants as $key => $value) {
285                $tmpArray[] = "$key: " . self::encode($value);
286            }
287
288            $result .= implode(', ', $tmpArray);
289        }
290
291        return $result . "}";
292    }
293
294
295    /**
296     * Encode the public methods of the ReflectionClass in the
297     * class2 format
298     *
299     * @param ReflectionClass $cls
300     * @return string Encoded method fragment
301     *
302     */
303    private static function _encodeMethods(ReflectionClass $cls)
304    {
305        $methods = $cls->getMethods();
306        $result = 'methods:{';
307
308        $started = false;
309        foreach ($methods as $method) {
310            if (! $method->isPublic() || !$method->isUserDefined()) {
311                continue;
312            }
313
314            if ($started) {
315                $result .= ',';
316            }
317            $started = true;
318
319            $result .= '' . $method->getName(). ':function(';
320
321            if ('__construct' != $method->getName()) {
322                $parameters  = $method->getParameters();
323                $paramCount  = count($parameters);
324                $argsStarted = false;
325
326                $argNames = "var argNames=[";
327                foreach ($parameters as $param) {
328                    if ($argsStarted) {
329                        $result .= ',';
330                    }
331
332                    $result .= $param->getName();
333
334                    if ($argsStarted) {
335                        $argNames .= ',';
336                    }
337
338                    $argNames .= '"' . $param->getName() . '"';
339
340                    $argsStarted = true;
341                }
342                $argNames .= "];";
343
344                $result .= "){"
345                         . $argNames
346                         . 'var result = ZAjaxEngine.invokeRemoteMethod('
347                         . "this, '" . $method->getName()
348                         . "',argNames,arguments);"
349                         . 'return(result);}';
350            } else {
351                $result .= "){}";
352            }
353        }
354
355        return $result . "}";
356    }
357
358
359    /**
360     * Encode the public properties of the ReflectionClass in the class2
361     * format.
362     *
363     * @param ReflectionClass $cls
364     * @return string Encode properties list
365     *
366     */
367    private static function _encodeVariables(ReflectionClass $cls)
368    {
369        $properties = $cls->getProperties();
370        $propValues = get_class_vars($cls->getName());
371        $result = "variables:{";
372        $cnt = 0;
373
374        $tmpArray = array();
375        foreach ($properties as $prop) {
376            if (! $prop->isPublic()) {
377                continue;
378            }
379
380            $tmpArray[] = $prop->getName()
381                        . ':'
382                        . self::encode($propValues[$prop->getName()]);
383        }
384        $result .= implode(',', $tmpArray);
385
386        return $result . "}";
387    }
388
389    /**
390     * Encodes the given $className into the class2 model of encoding PHP
391     * classes into JavaScript class2 classes.
392     * NOTE: Currently only public methods and variables are proxied onto
393     * the client machine
394     *
395     * @param string $className The name of the class, the class must be
396     *  instantiable using a null constructor
397     * @param string $package Optional package name appended to JavaScript
398     *  proxy class name
399     * @return string The class2 (JavaScript) encoding of the class
400     * @throws Zend_Json_Exception
401     */
402    public static function encodeClass($className, $package = '')
403    {
404        $cls = new ReflectionClass($className);
405        if (! $cls->isInstantiable()) {
406            require_once 'Zend/Json/Exception.php';
407            throw new Zend_Json_Exception("$className must be instantiable");
408        }
409
410        return "Class.create('$package$className',{"
411                . self::_encodeConstants($cls)    .","
412                . self::_encodeMethods($cls)      .","
413                . self::_encodeVariables($cls)    .'});';
414    }
415
416
417    /**
418     * Encode several classes at once
419     *
420     * Returns JSON encoded classes, using {@link encodeClass()}.
421     *
422     * @param array $classNames
423     * @param string $package
424     * @return string
425     */
426    public static function encodeClasses(array $classNames, $package = '')
427    {
428        $result = '';
429        foreach ($classNames as $className) {
430            $result .= self::encodeClass($className, $package);
431        }
432
433        return $result;
434    }
435
436    /**
437     * Encode Unicode Characters to \u0000 ASCII syntax.
438     *
439     * This algorithm was originally developed for the
440     * Solar Framework by Paul M. Jones
441     *
442     * @link   http://solarphp.com/
443     * @link   http://svn.solarphp.com/core/trunk/Solar/Json.php
444     * @param  string $value
445     * @return string
446     */
447    public static function encodeUnicodeString($value)
448    {
449        $strlen_var = strlen($value);
450        $ascii = "";
451
452        /**
453         * Iterate over every character in the string,
454         * escaping with a slash or encoding to UTF-8 where necessary
455         */
456        for($i = 0; $i < $strlen_var; $i++) {
457            $ord_var_c = ord($value[$i]);
458
459            switch (true) {
460                case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
461                    // characters U-00000000 - U-0000007F (same as ASCII)
462                    $ascii .= $value[$i];
463                    break;
464
465                case (($ord_var_c & 0xE0) == 0xC0):
466                    // characters U-00000080 - U-000007FF, mask 110XXXXX
467                    // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
468                    $char = pack('C*', $ord_var_c, ord($value[$i + 1]));
469                    $i += 1;
470                    $utf16 = self::_utf82utf16($char);
471                    $ascii .= sprintf('\u%04s', bin2hex($utf16));
472                    break;
473
474                case (($ord_var_c & 0xF0) == 0xE0):
475                    // characters U-00000800 - U-0000FFFF, mask 1110XXXX
476                    // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
477                    $char = pack('C*', $ord_var_c,
478                                 ord($value[$i + 1]),
479                                 ord($value[$i + 2]));
480                    $i += 2;
481                    $utf16 = self::_utf82utf16($char);
482                    $ascii .= sprintf('\u%04s', bin2hex($utf16));
483                    break;
484
485                case (($ord_var_c & 0xF8) == 0xF0):
486                    // characters U-00010000 - U-001FFFFF, mask 11110XXX
487                    // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
488                    $char = pack('C*', $ord_var_c,
489                                 ord($value[$i + 1]),
490                                 ord($value[$i + 2]),
491                                 ord($value[$i + 3]));
492                    $i += 3;
493                    $utf16 = self::_utf82utf16($char);
494                    $ascii .= sprintf('\u%04s', bin2hex($utf16));
495                    break;
496
497                case (($ord_var_c & 0xFC) == 0xF8):
498                    // characters U-00200000 - U-03FFFFFF, mask 111110XX
499                    // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
500                    $char = pack('C*', $ord_var_c,
501                                 ord($value[$i + 1]),
502                                 ord($value[$i + 2]),
503                                 ord($value[$i + 3]),
504                                 ord($value[$i + 4]));
505                    $i += 4;
506                    $utf16 = self::_utf82utf16($char);
507                    $ascii .= sprintf('\u%04s', bin2hex($utf16));
508                    break;
509
510                case (($ord_var_c & 0xFE) == 0xFC):
511                    // characters U-04000000 - U-7FFFFFFF, mask 1111110X
512                    // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
513                    $char = pack('C*', $ord_var_c,
514                                 ord($value[$i + 1]),
515                                 ord($value[$i + 2]),
516                                 ord($value[$i + 3]),
517                                 ord($value[$i + 4]),
518                                 ord($value[$i + 5]));
519                    $i += 5;
520                    $utf16 = self::_utf82utf16($char);
521                    $ascii .= sprintf('\u%04s', bin2hex($utf16));
522                    break;
523            }
524        }
525
526        return $ascii;
527     }
528
529    /**
530     * Convert a string from one UTF-8 char to one UTF-16 char.
531     *
532     * Normally should be handled by mb_convert_encoding, but
533     * provides a slower PHP-only method for installations
534     * that lack the multibye string extension.
535     *
536     * This method is from the Solar Framework by Paul M. Jones
537     *
538     * @link   http://solarphp.com
539     * @param string $utf8 UTF-8 character
540     * @return string UTF-16 character
541     */
542    protected static function _utf82utf16($utf8)
543    {
544        // Check for mb extension otherwise do by hand.
545        if( function_exists('mb_convert_encoding') ) {
546            return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
547        }
548
549        switch (strlen($utf8)) {
550            case 1:
551                // this case should never be reached, because we are in ASCII range
552                // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
553                return $utf8;
554
555            case 2:
556                // return a UTF-16 character from a 2-byte UTF-8 char
557                // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
558                return chr(0x07 & (ord($utf8{0}) >> 2))
559                     . chr((0xC0 & (ord($utf8{0}) << 6))
560                         | (0x3F & ord($utf8{1})));
561
562            case 3:
563                // return a UTF-16 character from a 3-byte UTF-8 char
564                // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
565                return chr((0xF0 & (ord($utf8{0}) << 4))
566                         | (0x0F & (ord($utf8{1}) >> 2)))
567                     . chr((0xC0 & (ord($utf8{1}) << 6))
568                         | (0x7F & ord($utf8{2})));
569        }
570
571        // ignoring UTF-32 for now, sorry
572        return '';
573    }
574}
575