3 * Zend Framework (http://framework.zend.com/)
5 * @link http://github.com/zendframework/zf2 for the canonical source repository
6 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license http://framework.zend.com/license/new-bsd New BSD License
13 use Zend\Json\Exception\InvalidArgumentException
;
14 use Zend\Json\Exception\RuntimeException
;
17 * Decode JSON encoded string to PHP variable constructs
23 * Parse tokens used to decode the JSON object. These are not
24 * for public consumption, they are just used internally to the
37 * Use to maintain a "pointer" to the source being decoded
44 * Caches the source length
48 protected $sourceLength;
51 * The offset within the source being decoded
59 * The current token being considered in the parser cycle
66 * Flag indicating how objects should be decoded
71 protected $decodeType;
76 protected $tokenValue;
81 * @param string $source String source to decode
82 * @param int $decodeType How objects should be decoded -- see
83 * {@link Zend\Json\Json::TYPE_ARRAY} and {@link Zend\Json\Json::TYPE_OBJECT} for
85 * @throws InvalidArgumentException
87 protected function __construct($source, $decodeType)
90 $this->source
= self
::decodeUnicodeString($source);
91 $this->sourceLength
= strlen($this->source
);
92 $this->token
= self
::EOF
;
95 switch ($decodeType) {
96 case Json
::TYPE_ARRAY
:
97 case Json
::TYPE_OBJECT
:
98 $this->decodeType
= $decodeType;
101 throw new InvalidArgumentException("Unknown decode type '{$decodeType}', please use one of the constants Json::TYPE_*");
104 // Set pointer at first token
105 $this->_getNextToken();
109 * Decode a JSON source string
111 * Decodes a JSON encoded string. The value returned will be one of the
119 * - array of one or more of the above types
121 * By default, decoded objects will be returned as associative arrays; to
122 * return a stdClass object instead, pass {@link Zend\Json\Json::TYPE_OBJECT} to
123 * the $objectDecodeType parameter.
127 * @param string $source String to be decoded
128 * @param int $objectDecodeType How objects should be decoded; should be
129 * either or {@link Zend\Json\Json::TYPE_ARRAY} or
130 * {@link Zend\Json\Json::TYPE_OBJECT}; defaults to TYPE_ARRAY
133 public static function decode($source, $objectDecodeType = Json
::TYPE_OBJECT
)
135 $decoder = new static($source, $objectDecodeType);
136 return $decoder->_decodeValue();
140 * Recursive driving routine for supported toplevel tops
144 protected function _decodeValue()
146 switch ($this->token
) {
148 $result = $this->tokenValue
;
149 $this->_getNextToken();
153 return($this->_decodeObject());
156 return($this->_decodeArray());
165 * Decodes an object of the form:
166 * { "attribute: value, "attribute2" : value,...}
168 * If Zend\Json\Encoder was used to encode the original object then
169 * a special attribute called __className which specifies a class
170 * name that should wrap the data contained within the encoded source.
172 * Decodes to either an array or stdClass object, based on the value of
173 * {@link $decodeType}. If invalid $decodeType present, returns as an
176 * @return array|stdClass
177 * @throws RuntimeException
179 protected function _decodeObject()
182 $tok = $this->_getNextToken();
184 while ($tok && $tok != self
::RBRACE
) {
185 if ($tok != self
::DATUM ||
! is_string($this->tokenValue
)) {
186 throw new RuntimeException('Missing key in object encoding: ' . $this->source
);
189 $key = $this->tokenValue
;
190 $tok = $this->_getNextToken();
192 if ($tok != self
::COLON
) {
193 throw new RuntimeException('Missing ":" in object encoding: ' . $this->source
);
196 $tok = $this->_getNextToken();
197 $members[$key] = $this->_decodeValue();
200 if ($tok == self
::RBRACE
) {
204 if ($tok != self
::COMMA
) {
205 throw new RuntimeException('Missing "," in object encoding: ' . $this->source
);
208 $tok = $this->_getNextToken();
211 switch ($this->decodeType
) {
212 case Json
::TYPE_OBJECT
:
213 // Create new stdClass and populate with $members
214 $result = new stdClass();
215 foreach ($members as $key => $value) {
219 $result->$key = $value;
222 case Json
::TYPE_ARRAY
:
228 $this->_getNextToken();
233 * Decodes a JSON array format:
234 * [element, element2,...,elementN]
237 * @throws RuntimeException
239 protected function _decodeArray()
242 $tok = $this->_getNextToken(); // Move past the '['
245 while ($tok && $tok != self
::RBRACKET
) {
246 $result[$index++
] = $this->_decodeValue();
250 if ($tok == self
::RBRACKET ||
!$tok) {
254 if ($tok != self
::COMMA
) {
255 throw new RuntimeException('Missing "," in array encoding: ' . $this->source
);
258 $tok = $this->_getNextToken();
261 $this->_getNextToken();
267 * Removes whitespace characters from the source input
269 protected function _eatWhitespace()
272 '/([\t\b\f\n\r ])*/s',
277 && $matches[0][1] == $this->offset
)
279 $this->offset +
= strlen($matches[0][0]);
285 * Retrieves the next token from the source stream
287 * @return int Token constant value specified in class definition
288 * @throws RuntimeException
290 protected function _getNextToken()
292 $this->token
= self
::EOF
;
293 $this->tokenValue
= null;
294 $this->_eatWhitespace();
296 if ($this->offset
>= $this->sourceLength
) {
300 $str = $this->source
;
301 $strLength = $this->sourceLength
;
307 $this->token
= self
::LBRACE
;
310 $this->token
= self
::RBRACE
;
313 $this->token
= self
::LBRACKET
;
316 $this->token
= self
::RBRACKET
;
319 $this->token
= self
::COMMA
;
322 $this->token
= self
::COLON
;
328 if ($i >= $strLength) {
336 if ($i >= $strLength) {
369 throw new RuntimeException("Illegal escape sequence '{$chr}'");
371 } elseif ($chr == '"') {
376 } while ($i < $strLength);
378 $this->token
= self
::DATUM
;
379 //$this->tokenValue = substr($str, $start + 1, $i - $start - 1);
380 $this->tokenValue
= $result;
383 if (($i+
3) < $strLength && substr($str, $start, 4) == "true") {
384 $this->token
= self
::DATUM
;
386 $this->tokenValue
= true;
390 if (($i+
4) < $strLength && substr($str, $start, 5) == "false") {
391 $this->token
= self
::DATUM
;
393 $this->tokenValue
= false;
397 if (($i+
3) < $strLength && substr($str, $start, 4) == "null") {
398 $this->token
= self
::DATUM
;
400 $this->tokenValue
= NULL;
405 if ($this->token
!= self
::EOF
) {
406 $this->offset
= $i +
1; // Consume the last token character
407 return($this->token
);
411 if ($chr == '-' ||
$chr == '.' ||
($chr >= '0' && $chr <= '9')) {
412 if (preg_match('/-?([0-9])*(\.[0-9]*)?((e|E)((-|\+)?)[0-9]+)?/s',
413 $str, $matches, PREG_OFFSET_CAPTURE
, $start) && $matches[0][1] == $start) {
415 $datum = $matches[0][0];
417 if (is_numeric($datum)) {
418 if (preg_match('/^0\d+$/', $datum)) {
419 throw new RuntimeException("Octal notation not supported by JSON (value: {$datum})");
421 $val = intval($datum);
422 $fVal = floatval($datum);
423 $this->tokenValue
= ($val == $fVal ?
$val : $fVal);
426 throw new RuntimeException("Illegal number format: {$datum}");
429 $this->token
= self
::DATUM
;
430 $this->offset
= $start +
strlen($datum);
433 throw new RuntimeException('Illegal Token');
440 * Decode Unicode Characters from \u0000 ASCII syntax.
442 * This algorithm was originally developed for the
443 * Solar Framework by Paul M. Jones
445 * @link http://solarphp.com/
446 * @link http://svn.solarphp.com/core/trunk/Solar/Json.php
447 * @param string $chrs
450 public static function decodeUnicodeString($chrs)
452 $chrs = (string) $chrs;
454 $strlenChrs = strlen($chrs);
456 for ($i = 0; $i < $strlenChrs; $i++
) {
457 $ordChrsC = ord($chrs[$i]);
460 case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $i, 6)):
461 // single, escaped unicode character
462 $utf16 = chr(hexdec(substr($chrs, ($i +
2), 2)))
463 . chr(hexdec(substr($chrs, ($i +
4), 2)));
464 $utf8char = self
::_utf162utf8($utf16);
465 $search = array('\\', "\n", "\t", "\r", chr(0x08), chr(0x0C), '"', '\'', '/');
466 if (in_array($utf8char, $search)) {
467 $replace = array('\\\\', '\\n', '\\t', '\\r', '\\b', '\\f', '\\"', '\\\'', '\\/');
468 $utf8char = str_replace($search, $replace, $utf8char);
473 case ($ordChrsC >= 0x20) && ($ordChrsC <= 0x7F):
476 case ($ordChrsC & 0xE0) == 0xC0:
477 // characters U-00000080 - U-000007FF, mask 110XXXXX
478 //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
479 $utf8 .= substr($chrs, $i, 2);
482 case ($ordChrsC & 0xF0) == 0xE0:
483 // characters U-00000800 - U-0000FFFF, mask 1110XXXX
484 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
485 $utf8 .= substr($chrs, $i, 3);
488 case ($ordChrsC & 0xF8) == 0xF0:
489 // characters U-00010000 - U-001FFFFF, mask 11110XXX
490 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
491 $utf8 .= substr($chrs, $i, 4);
494 case ($ordChrsC & 0xFC) == 0xF8:
495 // characters U-00200000 - U-03FFFFFF, mask 111110XX
496 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
497 $utf8 .= substr($chrs, $i, 5);
500 case ($ordChrsC & 0xFE) == 0xFC:
501 // characters U-04000000 - U-7FFFFFFF, mask 1111110X
502 // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
503 $utf8 .= substr($chrs, $i, 6);
513 * Convert a string from one UTF-16 char to one UTF-8 char.
515 * Normally should be handled by mb_convert_encoding, but
516 * provides a slower PHP-only method for installations
517 * that lack the multibyte string extension.
519 * This method is from the Solar Framework by Paul M. Jones
521 * @link http://solarphp.com
522 * @param string $utf16 UTF-16 character
523 * @return string UTF-8 character
525 protected static function _utf162utf8($utf16)
527 // Check for mb extension otherwise do by hand.
528 if (function_exists('mb_convert_encoding')) {
529 return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
532 $bytes = (ord($utf16{0}) << 8) |
ord($utf16{1});
535 case ((0x7F & $bytes) == $bytes):
536 // this case should never be reached, because we are in ASCII range
537 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
538 return chr(0x7F & $bytes);
540 case (0x07FF & $bytes) == $bytes:
541 // return a 2-byte UTF-8 character
542 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
543 return chr(0xC0 |
(($bytes >> 6) & 0x1F))
544 . chr(0x80 |
($bytes & 0x3F));
546 case (0xFFFF & $bytes) == $bytes:
547 // return a 3-byte UTF-8 character
548 // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
549 return chr(0xE0 |
(($bytes >> 12) & 0x0F))
550 . chr(0x80 |
(($bytes >> 6) & 0x3F))
551 . chr(0x80 |
($bytes & 0x3F));
554 // ignoring UTF-32 for now, sorry