laravel-6 support

This commit is contained in:
RafficMohammed
2023-01-08 01:17:22 +05:30
parent 1a5c16ae4b
commit 774eed8b0e
4962 changed files with 279380 additions and 297961 deletions

View File

@@ -1,174 +0,0 @@
# Changelog
All notable changes to this project will be documented in this file, in reverse chronological order by release.
## 3.1.2 - 2019-10-09
### Added
- Nothing.
### Changed
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#46](https://github.com/zendframework/zend-json/pull/46) changes
curly braces in array and string offset access to square brackets
in order to prevent issues under the upcoming PHP 7.4 release.
- [#37](https://github.com/zendframework/zend-json/pull/37) fixes
output of `\Zend\Json::prettyPrint` to not remove spaces after
commas in value.
## 3.1.1 - 2019-06-18
### Added
- [#44](https://github.com/zendframework/zend-json/pull/44) adds support for PHP 7.3.
### Changed
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Nothing.
## 3.1.0 - 2018-01-04
### Added
- [#35](https://github.com/zendframework/zend-json/pull/35) and
[#39](https://github.com/zendframework/zend-json/pull/39) add support for PHP
7.1 and PHP 7.2.
### Deprecated
- Nothing.
### Removed
- [#35](https://github.com/zendframework/zend-json/pull/35) removes support for
PHP 5.5.
- [#35](https://github.com/zendframework/zend-json/pull/35) removes support for
HHVM.
### Fixed
- [#38](https://github.com/zendframework/zend-json/pull/38) provides a fix to
`Json::prettyPrint()` to ensure that empty arrays and objects are printed
without newlines.
- [#38](https://github.com/zendframework/zend-json/pull/38) provides a fix to
`Json::prettyPrint()` to remove additional newlines preceding a closing
bracket.
## 3.0.0 - 2016-03-31
### Added
- [#21](https://github.com/zendframework/zend-json/pull/21) adds documentation
and publishes it to https://zendframework.github.io/zend-json/
### Deprecated
- Nothing.
### Removed
- [#20](https://github.com/zendframework/zend-json/pull/20) removes the
`Zend\Json\Server` subcomponent, which has been extracted to
[zend-json-server](https://zendframework.github.io/zend-json-server/).
If you use that functionality, install the new component.
- [#21](https://github.com/zendframework/zend-json/pull/21) removes the
`Zend\Json\Json::fromXml()` functionality, which has been extracted to
[zend-xml2json](https://zendframework.github.io/zend-xml2json/). If you used
this functionality, you will need to install the new package, and rewrite
calls to `Zend\Json\Json::fromXml()` to `Zend\Xml2Json\Xml2Json::fromXml()`.
- [#20](https://github.com/zendframework/zend-json/pull/20) and
[#21](https://github.com/zendframework/zend-json/pull/21) removes dependencies
on zendframework/zendxml, zendframework/zend-stdlib,
zendframework/zend-server, and zendframework-zend-http, due to the above
listed component extractions.
### Fixed
- Nothing.
## 2.6.1 - 2016-02-04
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#18](https://github.com/zendframework/zend-json/pull/18) updates dependencies
to allow usage on PHP 7, as well as with zend-stdlib v3.
## 2.6.0 - 2015-11-18
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- [#5](https://github.com/zendframework/zend-json/pull/5) removes
zendframework/zend-stdlib as a required dependency, marking it instead
optional, as it is only used for the `Server` subcomponent.
### Fixed
- Nothing.
## 2.5.2 - 2015-08-05
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#3](https://github.com/zendframework/zend-json/pull/3) fixes an array key
name from `intent` to `indent` to ensure indentation works correctly during
pretty printing.

View File

@@ -1,27 +0,0 @@
Copyright (c) 2005-2019, Zend Technologies USA, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
- Neither the name of Zend Technologies USA, Inc. nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@@ -1,27 +0,0 @@
# zend-json
[![Build Status](https://secure.travis-ci.org/zendframework/zend-json.svg?branch=master)](https://secure.travis-ci.org/zendframework/zend-json)
[![Coverage Status](https://coveralls.io/repos/github/zendframework/zend-json/badge.svg?branch=master)](https://coveralls.io/github/zendframework/zend-json?branch=master)
`Zend\Json` provides convenience methods for serializing native PHP to JSON and
decoding JSON to native PHP. For more information on JSON, visit the JSON
[project site](http://www.json.org/).
## Installation
Run the following to install this library:
```bash
$ composer require zendframework/zend-json
```
## Documentation
Browse the documentation online at https://docs.zendframework.com/zend-json/
## Support
* [Issues](https://github.com/zendframework/zend-json/issues/)
* [Chat](https://zendframework-slack.herokuapp.com/)
* [Forum](https://discourse.zendframework.com/)

View File

@@ -1,59 +0,0 @@
{
"name": "zendframework/zend-json",
"description": "provides convenience methods for serializing native PHP to JSON and decoding JSON to native PHP",
"license": "BSD-3-Clause",
"keywords": [
"zf",
"zendframework",
"json"
],
"support": {
"docs": "https://docs.zendframework.com/zend-json/",
"issues": "https://github.com/zendframework/zend-json/issues",
"source": "https://github.com/zendframework/zend-json",
"rss": "https://github.com/zendframework/zend-json/releases.atom",
"chat": "https://zendframework-slack.herokuapp.com",
"forum": "https://discourse.zendframework.com/c/questions/components"
},
"require": {
"php": "^5.6 || ^7.0"
},
"require-dev": {
"phpunit/phpunit": "^5.7.23 || ^6.4.3",
"zendframework/zend-coding-standard": "~1.0.0",
"zendframework/zend-stdlib": "^2.7.7 || ^3.1"
},
"suggest": {
"zendframework/zend-json-server": "For implementing JSON-RPC servers",
"zendframework/zend-xml2json": "For converting XML documents to JSON"
},
"autoload": {
"psr-4": {
"Zend\\Json\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"ZendTest\\Json\\": "test/"
}
},
"config": {
"sort-packages": true
},
"extra": {
"branch-alias": {
"dev-master": "3.1.x-dev",
"dev-develop": "3.2.x-dev"
}
},
"scripts": {
"check": [
"@cs-check",
"@test"
],
"cs-check": "phpcs",
"cs-fix": "phpcbf",
"test": "phpunit --colors=always",
"test-coverage": "phpunit --colors=always --coverage-clover clover.xml"
}
}

View File

@@ -1,549 +0,0 @@
<?php
/**
* @see https://github.com/zendframework/zend-json for the canonical source repository
* @copyright Copyright (c) 2005-2018 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-json/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Json;
use stdClass;
use Zend\Json\Exception\InvalidArgumentException;
use Zend\Json\Exception\RuntimeException;
/**
* Decode JSON encoded string to PHP variable constructs
*/
class Decoder
{
/**
* Parse tokens used to decode the JSON object. These are not
* for public consumption, they are just used internally to the
* class.
*/
const EOF = 0;
const DATUM = 1;
const LBRACE = 2;
const LBRACKET = 3;
const RBRACE = 4;
const RBRACKET = 5;
const COMMA = 6;
const COLON = 7;
/**
* Use to maintain a "pointer" to the source being decoded
*
* @var string
*/
protected $source;
/**
* Caches the source length
*
* @var int
*/
protected $sourceLength;
/**
* The offset within the source being decoded
*
* @var int
*
*/
protected $offset;
/**
* The current token being considered in the parser cycle
*
* @var int
*/
protected $token;
/**
* Flag indicating how objects should be decoded
*
* @var int
* @access protected
*/
protected $decodeType;
/**
* @var mixed
*/
protected $tokenValue;
/**
* Decode Unicode Characters from \u0000 ASCII syntax.
*
* This algorithm was originally developed for the
* Solar Framework by Paul M. Jones
*
* @link http://solarphp.com/
* @link https://github.com/solarphp/core/blob/master/Solar/Json.php
* @param string $chrs
* @return string
*/
public static function decodeUnicodeString($chrs)
{
$chrs = (string) $chrs;
$utf8 = '';
$strlenChrs = strlen($chrs);
for ($i = 0; $i < $strlenChrs; $i++) {
$ordChrsC = ord($chrs[$i]);
switch (true) {
case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $i, 6)):
// single, escaped unicode character
$utf16 = chr(hexdec(substr($chrs, ($i + 2), 2)))
. chr(hexdec(substr($chrs, ($i + 4), 2)));
$utf8char = self::utf162utf8($utf16);
$search = ['\\', "\n", "\t", "\r", chr(0x08), chr(0x0C), '"', '\'', '/'];
if (in_array($utf8char, $search)) {
$replace = ['\\\\', '\\n', '\\t', '\\r', '\\b', '\\f', '\\"', '\\\'', '\\/'];
$utf8char = str_replace($search, $replace, $utf8char);
}
$utf8 .= $utf8char;
$i += 5;
break;
case ($ordChrsC >= 0x20) && ($ordChrsC <= 0x7F):
$utf8 .= $chrs[$i];
break;
case ($ordChrsC & 0xE0) == 0xC0:
// characters U-00000080 - U-000007FF, mask 110XXXXX
//see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $i, 2);
++$i;
break;
case ($ordChrsC & 0xF0) == 0xE0:
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $i, 3);
$i += 2;
break;
case ($ordChrsC & 0xF8) == 0xF0:
// characters U-00010000 - U-001FFFFF, mask 11110XXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $i, 4);
$i += 3;
break;
case ($ordChrsC & 0xFC) == 0xF8:
// characters U-00200000 - U-03FFFFFF, mask 111110XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $i, 5);
$i += 4;
break;
case ($ordChrsC & 0xFE) == 0xFC:
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $i, 6);
$i += 5;
break;
}
}
return $utf8;
}
/**
* Constructor
*
* @param string $source String source to decode
* @param int $decodeType How objects should be decoded -- see
* {@link Json::TYPE_ARRAY} and {@link Json::TYPE_OBJECT} for * valid
* values
* @throws InvalidArgumentException
*/
protected function __construct($source, $decodeType)
{
// Set defaults
$this->source = self::decodeUnicodeString($source);
$this->sourceLength = strlen($this->source);
$this->token = self::EOF;
$this->offset = 0;
switch ($decodeType) {
case Json::TYPE_ARRAY:
case Json::TYPE_OBJECT:
$this->decodeType = $decodeType;
break;
default:
throw new InvalidArgumentException(sprintf(
'Unknown decode type "%s", please use one of the Json::TYPE_* constants',
$decodeType
));
}
// Set pointer at first token
$this->getNextToken();
}
/**
* Decode a JSON source string.
*
* Decodes a JSON encoded string; the value returned will be one of the
* following:
*
* - integer
* - float
* - boolean
* - null
* - stdClass
* - array
* - array of one or more of the above types
*
* By default, decoded objects will be returned as a stdClass object;
* to return associative arrays instead, pass {@link Json::TYPE_ARRAY}
* to the $objectDecodeType parameter.
*
* @param string $source String to be decoded.
* @param int $objectDecodeType How objects should be decoded; should be
* either or {@link Json::TYPE_ARRAY} or {@link Json::TYPE_OBJECT};
* defaults to Json::TYPE_OBJECT.
* @return mixed
*/
public static function decode($source, $objectDecodeType = Json::TYPE_OBJECT)
{
$decoder = new static($source, $objectDecodeType);
return $decoder->decodeValue();
}
/**
* Recursive routine for supported toplevel types.
*
* @return mixed
*/
protected function decodeValue()
{
switch ($this->token) {
case self::DATUM:
$result = $this->tokenValue;
$this->getNextToken();
return($result);
case self::LBRACE:
return($this->decodeObject());
case self::LBRACKET:
return($this->decodeArray());
default:
return;
}
}
/**
* Decodes an object of the form { "attribute: value, "attribute2" : value, ... }
*
* If Zend\Json\Encoder was used to encode the original object, then
* a special attribute called __className will specify a class
* name with which to wrap the data contained within the encoded source.
*
* Decodes to either an array or stdClass object, based on the value of
* {@link $decodeType}. If invalid $decodeType present, returns as an
* array.
*
* @return array|stdClass
* @throws RuntimeException
*/
protected function decodeObject()
{
$members = [];
$tok = $this->getNextToken();
while ($tok && $tok !== self::RBRACE) {
if ($tok !== self::DATUM || ! is_string($this->tokenValue)) {
throw new RuntimeException(sprintf('Missing key in object encoding: %s', $this->source));
}
$key = $this->tokenValue;
$tok = $this->getNextToken();
if ($tok !== self::COLON) {
throw new RuntimeException(sprintf('Missing ":" in object encoding: %s', $this->source));
}
$this->getNextToken();
$members[$key] = $this->decodeValue();
$tok = $this->token;
if ($tok === self::RBRACE) {
break;
}
if ($tok !== self::COMMA) {
throw new RuntimeException(sprintf('Missing "," in object encoding: %s', $this->source));
}
$tok = $this->getNextToken();
}
switch ($this->decodeType) {
case Json::TYPE_OBJECT:
// Create new stdClass and populate with $members
$result = new stdClass();
foreach ($members as $key => $value) {
if ($key === '') {
$key = '_empty_';
}
$result->$key = $value;
}
break;
case Json::TYPE_ARRAY:
// intentionally fall-through
default:
$result = $members;
break;
}
$this->getNextToken();
return $result;
}
/**
* Decodes the JSON array format [element, element2, ..., elementN]
*
* @return array
* @throws RuntimeException
*/
protected function decodeArray()
{
$result = [];
$tok = $this->getNextToken(); // Move past the '['
$index = 0;
while ($tok && $tok !== self::RBRACKET) {
$result[$index++] = $this->decodeValue();
$tok = $this->token;
if ($tok == self::RBRACKET || ! $tok) {
break;
}
if ($tok !== self::COMMA) {
throw new RuntimeException(sprintf('Missing "," in array encoding: %s', $this->source));
}
$tok = $this->getNextToken();
}
$this->getNextToken();
return $result;
}
/**
* Removes whitespace characters from the source input.
*/
protected function eatWhitespace()
{
if (preg_match('/([\t\b\f\n\r ])*/s', $this->source, $matches, PREG_OFFSET_CAPTURE, $this->offset)
&& $matches[0][1] == $this->offset
) {
$this->offset += strlen($matches[0][0]);
}
}
/**
* Retrieves the next token from the source stream.
*
* @return int Token constant value specified in class definition.
* @throws RuntimeException
*/
protected function getNextToken()
{
$this->token = self::EOF;
$this->tokenValue = null;
$this->eatWhitespace();
if ($this->offset >= $this->sourceLength) {
return(self::EOF);
}
$str = $this->source;
$strLength = $this->sourceLength;
$i = $this->offset;
$start = $i;
switch ($str[$i]) {
case '{':
$this->token = self::LBRACE;
break;
case '}':
$this->token = self::RBRACE;
break;
case '[':
$this->token = self::LBRACKET;
break;
case ']':
$this->token = self::RBRACKET;
break;
case ',':
$this->token = self::COMMA;
break;
case ':':
$this->token = self::COLON;
break;
case '"':
$result = '';
do {
$i++;
if ($i >= $strLength) {
break;
}
$chr = $str[$i];
if ($chr === '"') {
break;
}
if ($chr !== '\\') {
$result .= $chr;
continue;
}
$i++;
if ($i >= $strLength) {
break;
}
$chr = $str[$i];
switch ($chr) {
case '"':
$result .= '"';
break;
case '\\':
$result .= '\\';
break;
case '/':
$result .= '/';
break;
case 'b':
$result .= "\x08";
break;
case 'f':
$result .= "\x0c";
break;
case 'n':
$result .= "\x0a";
break;
case 'r':
$result .= "\x0d";
break;
case 't':
$result .= "\x09";
break;
case '\'':
$result .= '\'';
break;
default:
throw new RuntimeException(sprintf('Illegal escape sequence "%s"', $chr));
}
} while ($i < $strLength);
$this->token = self::DATUM;
$this->tokenValue = $result;
break;
case 't':
if (($i + 3) < $strLength && $start === strpos($str, "true", $start)) {
$this->token = self::DATUM;
}
$this->tokenValue = true;
$i += 3;
break;
case 'f':
if (($i + 4) < $strLength && $start === strpos($str, "false", $start)) {
$this->token = self::DATUM;
}
$this->tokenValue = false;
$i += 4;
break;
case 'n':
if (($i + 3) < $strLength && $start === strpos($str, "null", $start)) {
$this->token = self::DATUM;
}
$this->tokenValue = null;
$i += 3;
break;
}
if ($this->token !== self::EOF) {
$this->offset = $i + 1; // Consume the last token character
return ($this->token);
}
$chr = $str[$i];
if ($chr !== '-' && $chr !== '.' && ($chr < '0' || $chr > '9')) {
throw new RuntimeException('Illegal Token');
}
if (preg_match('/-?([0-9])*(\.[0-9]*)?((e|E)((-|\+)?)[0-9]+)?/s', $str, $matches, PREG_OFFSET_CAPTURE, $start)
&& $matches[0][1] == $start
) {
$datum = $matches[0][0];
if (! is_numeric($datum)) {
throw new RuntimeException(sprintf('Illegal number format: %s', $datum));
}
if (preg_match('/^0\d+$/', $datum)) {
throw new RuntimeException(sprintf('Octal notation not supported by JSON (value: %o)', $datum));
}
$val = intval($datum);
$fVal = floatval($datum);
$this->tokenValue = ($val == $fVal ? $val : $fVal);
$this->token = self::DATUM;
$this->offset = $start + strlen($datum);
}
return $this->token;
}
/**
* Convert a string from one UTF-16 char to one UTF-8 char.
*
* Normally should be handled by mb_convert_encoding, but provides a slower
* PHP-only method for installations that lack the multibyte string
* extension.
*
* This method is from the Solar Framework by Paul M. Jones.
*
* @link http://solarphp.com
* @param string $utf16 UTF-16 character
* @return string UTF-8 character
*/
protected static function utf162utf8($utf16)
{
// Check for mb extension otherwise do by hand.
if (function_exists('mb_convert_encoding')) {
return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
}
$bytes = (ord($utf16[0]) << 8) | ord($utf16[1]);
switch (true) {
case ((0x7F & $bytes) == $bytes):
// This case should never be reached, because we are in ASCII range;
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0x7F & $bytes);
case (0x07FF & $bytes) == $bytes:
// Return a 2-byte UTF-8 character;
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0xC0 | (($bytes >> 6) & 0x1F))
. chr(0x80 | ($bytes & 0x3F));
case (0xFFFF & $bytes) == $bytes:
// Return a 3-byte UTF-8 character;
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0xE0 | (($bytes >> 12) & 0x0F))
. chr(0x80 | (($bytes >> 6) & 0x3F))
. chr(0x80 | ($bytes & 0x3F));
}
// ignoring UTF-32 for now, sorry
return '';
}
}

View File

@@ -1,601 +0,0 @@
<?php
/**
* @see https://github.com/zendframework/zend-json for the canonical source repository
* @copyright Copyright (c) 2005-2018 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-json/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Json;
use Iterator;
use IteratorAggregate;
use JsonSerializable;
use ReflectionClass;
use Zend\Json\Exception\InvalidArgumentException;
use Zend\Json\Exception\RecursionException;
/**
* Encode PHP constructs to JSON.
*/
class Encoder
{
/**
* Whether or not to check for possible cycling.
*
* @var bool
*/
protected $cycleCheck;
/**
* Additional options used during encoding.
*
* @var array
*/
protected $options = [];
/**
* Array of visited objects; used to prevent cycling.
*
* @var array
*/
protected $visited = [];
/**
* @param bool $cycleCheck Whether or not to check for recursion when encoding.
* @param array $options Additional options used during encoding.
*/
protected function __construct($cycleCheck = false, array $options = [])
{
$this->cycleCheck = $cycleCheck;
$this->options = $options;
}
/**
* Use the JSON encoding scheme for the value specified.
*
* @param mixed $value The value to be encoded.
* @param bool $cycleCheck Whether or not to check for possible object recursion when encoding.
* @param array $options Additional options used during encoding.
* @return string The encoded value.
*/
public static function encode($value, $cycleCheck = false, array $options = [])
{
$encoder = new static($cycleCheck, $options);
if ($value instanceof JsonSerializable) {
$value = $value->jsonSerialize();
}
return $encoder->encodeValue($value);
}
/**
* Encode a value to JSON.
*
* Recursive method which determines the type of value to be encoded
* and then dispatches to the appropriate method.
*
* $values are either
* - objects (returns from {@link encodeObject()})
* - arrays (returns from {@link encodeArray()})
* - scalars (returns from {@link encodeDatum()})
*
* @param $value mixed The value to be encoded.
* @return string Encoded value.
*/
protected function encodeValue(&$value)
{
if (is_object($value)) {
return $this->encodeObject($value);
}
if (is_array($value)) {
return $this->encodeArray($value);
}
return $this->encodeDatum($value);
}
/**
* Encode an object to JSON by encoding each of the public properties.
*
* A special property is added to the JSON object called '__className' that
* contains the classname of $value; this can be used by consumers of the
* resulting JSON to cast to the specific class.
*
* @param $value object
* @return string
* @throws RecursionException If recursive checks are enabled and the
* object has been serialized previously.
*/
protected function encodeObject(&$value)
{
if ($this->cycleCheck) {
if ($this->wasVisited($value)) {
if (! isset($this->options['silenceCyclicalExceptions'])
|| $this->options['silenceCyclicalExceptions'] !== true
) {
throw new RecursionException(sprintf(
'Cycles not supported in JSON encoding; cycle introduced by class "%s"',
get_class($value)
));
}
return '"* RECURSION (' . str_replace('\\', '\\\\', get_class($value)) . ') *"';
}
$this->visited[] = $value;
}
$props = '';
if (method_exists($value, 'toJson')) {
$props = ',' . preg_replace("/^\{(.*)\}$/", "\\1", $value->toJson());
} else {
if ($value instanceof IteratorAggregate) {
$propCollection = $value->getIterator();
} elseif ($value instanceof Iterator) {
$propCollection = $value;
} else {
$propCollection = get_object_vars($value);
}
foreach ($propCollection as $name => $propValue) {
if (! isset($propValue)) {
continue;
}
$props .= ','
. $this->encodeValue($name)
. ':'
. $this->encodeValue($propValue);
}
}
$className = get_class($value);
return '{"__className":'
. $this->encodeString($className)
. $props . '}';
}
/**
* Determine if an object has been serialized already.
*
* @param mixed $value
* @return bool
*/
protected function wasVisited(&$value)
{
if (in_array($value, $this->visited, true)) {
return true;
}
return false;
}
/**
* JSON encode an array value.
*
* Recursively encodes each value of an array and returns a JSON encoded
* array string.
*
* Arrays are defined as integer-indexed arrays starting at index 0, where
* the last index is (count($array) -1); any deviation from that is
* considered an associative array, and will be passed to
* {@link encodeAssociativeArray()}.
*
* @param $array array
* @return string
*/
protected function encodeArray($array)
{
// Check for associative array
if (! empty($array) && (array_keys($array) !== range(0, count($array) - 1))) {
// Associative array
return $this->encodeAssociativeArray($array);
}
// Indexed array
$tmpArray = [];
$result = '[';
$length = count($array);
for ($i = 0; $i < $length; $i++) {
$tmpArray[] = $this->encodeValue($array[$i]);
}
$result .= implode(',', $tmpArray);
$result .= ']';
return $result;
}
/**
* Encode an associative array to JSON.
*
* JSON does not have a concept of associative arrays; as such, we encode
* them to objects.
*
* @param array $array Array to encode.
* @return string
*/
protected function encodeAssociativeArray($array)
{
$tmpArray = [];
$result = '{';
foreach ($array as $key => $value) {
$tmpArray[] = sprintf(
'%s:%s',
$this->encodeString((string) $key),
$this->encodeValue($value)
);
}
$result .= implode(',', $tmpArray);
$result .= '}';
return $result;
}
/**
* JSON encode a scalar data type (string, number, boolean, null).
*
* If value type is not a string, number, boolean, or null, the string
* 'null' is returned.
*
* @param mixed $value
* @return string
*/
protected function encodeDatum($value)
{
if (is_int($value) || is_float($value)) {
return str_replace(',', '.', (string) $value);
}
if (is_string($value)) {
return $this->encodeString($value);
}
if (is_bool($value)) {
return $value ? 'true' : 'false';
}
return 'null';
}
/**
* JSON encode a string value by escaping characters as necessary.
*
* @param string $string
* @return string
*/
protected function encodeString($string)
{
// @codingStandardsIgnoreStart
// Escape these characters with a backslash or unicode escape:
// " \ / \n \r \t \b \f
$search = ['\\', "\n", "\t", "\r", "\b", "\f", '"', '\'', '&', '<', '>', '/'];
$replace = ['\\\\', '\\n', '\\t', '\\r', '\\b', '\\f', '\\u0022', '\\u0027', '\\u0026', '\\u003C', '\\u003E', '\\/'];
$string = str_replace($search, $replace, $string);
// @codingStandardsIgnoreEnd
// Escape certain ASCII characters:
// 0x08 => \b
// 0x0c => \f
$string = str_replace([chr(0x08), chr(0x0C)], ['\b', '\f'], $string);
$string = self::encodeUnicodeString($string);
return '"' . $string . '"';
}
/**
* Encode the constants associated with the ReflectionClass parameter.
*
* The encoding format is based on the class2 format.
*
* @param ReflectionClass $class
* @return string Encoded constant block in class2 format
*/
private static function encodeConstants(ReflectionClass $class)
{
$result = "constants:{";
$constants = $class->getConstants();
if (empty($constants)) {
return $result . '}';
}
$tmpArray = [];
foreach ($constants as $key => $value) {
$tmpArray[] = sprintf('%s: %s', $key, self::encode($value));
}
$result .= implode(', ', $tmpArray);
return $result . "}";
}
/**
* Encode the public methods of the ReflectionClass in the class2 format
*
* @param ReflectionClass $class
* @return string Encoded method fragment.
*/
private static function encodeMethods(ReflectionClass $class)
{
$result = 'methods:{';
$started = false;
foreach ($class->getMethods() as $method) {
if (! $method->isPublic() || ! $method->isUserDefined()) {
continue;
}
if ($started) {
$result .= ',';
}
$started = true;
$result .= sprintf('%s:function(', $method->getName());
if ('__construct' === $method->getName()) {
$result .= '){}';
continue;
}
$argsStarted = false;
$argNames = "var argNames=[";
foreach ($method->getParameters() as $param) {
if ($argsStarted) {
$result .= ',';
}
$result .= $param->getName();
if ($argsStarted) {
$argNames .= ',';
}
$argNames .= sprintf('"%s"', $param->getName());
$argsStarted = true;
}
$argNames .= "];";
$result .= "){"
. $argNames
. 'var result = ZAjaxEngine.invokeRemoteMethod('
. "this, '"
. $method->getName()
. "',argNames,arguments);"
. 'return(result);}';
}
return $result . "}";
}
/**
* Encode the public properties of the ReflectionClass in the class2 format.
*
* @param ReflectionClass $class
* @return string Encode properties list
*
*/
private static function encodeVariables(ReflectionClass $class)
{
$propValues = get_class_vars($class->getName());
$result = "variables:{";
$tmpArray = [];
foreach ($class->getProperties() as $prop) {
if (! $prop->isPublic()) {
continue;
}
$name = $prop->getName();
$tmpArray[] = sprintf('%s:%s', $name, self::encode($propValues[$name]));
}
$result .= implode(',', $tmpArray);
return $result . "}";
}
/**
* Encodes the given $className into the class2 model of encoding PHP classes into JavaScript class2 classes.
*
* NOTE: Currently only public methods and variables are proxied onto the
* client machine
*
* @param $className string The name of the class, the class must be
* instantiable using a null constructor.
* @param $package string Optional package name appended to JavaScript
* proxy class name.
* @return string The class2 (JavaScript) encoding of the class.
* @throws InvalidArgumentException
*/
public static function encodeClass($className, $package = '')
{
$class = new ReflectionClass($className);
if (! $class->isInstantiable()) {
throw new InvalidArgumentException(sprintf(
'"%s" must be instantiable',
$className
));
}
return sprintf(
'Class.create(\'%s%s\',{%s,%s,%s});',
$package,
$className,
self::encodeConstants($class),
self::encodeMethods($class),
self::encodeVariables($class)
);
}
/**
* Encode several classes at once.
*
* Returns JSON encoded classes, using {@link encodeClass()}.
*
* @param string[] $classNames
* @param string $package
* @return string
*/
public static function encodeClasses(array $classNames, $package = '')
{
$result = '';
foreach ($classNames as $className) {
$result .= static::encodeClass($className, $package);
}
return $result;
}
/**
* Encode Unicode Characters to \u0000 ASCII syntax.
*
* This algorithm was originally developed for the Solar Framework by Paul
* M. Jones.
*
* @link http://solarphp.com/
* @link https://github.com/solarphp/core/blob/master/Solar/Json.php
* @param string $value
* @return string
*/
public static function encodeUnicodeString($value)
{
$strlenVar = strlen($value);
$ascii = "";
// Iterate over every character in the string, escaping with a slash or
// encoding to UTF-8 where necessary.
for ($i = 0; $i < $strlenVar; $i++) {
$ordVarC = ord($value[$i]);
switch (true) {
case (($ordVarC >= 0x20) && ($ordVarC <= 0x7F)):
// characters U-00000000 - U-0000007F (same as ASCII)
$ascii .= $value[$i];
break;
case (($ordVarC & 0xE0) == 0xC0):
// characters U-00000080 - U-000007FF, mask 110XXXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ordVarC, ord($value[$i + 1]));
$i += 1;
$utf16 = self::utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ordVarC & 0xF0) == 0xE0):
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack(
'C*',
$ordVarC,
ord($value[$i + 1]),
ord($value[$i + 2])
);
$i += 2;
$utf16 = self::utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ordVarC & 0xF8) == 0xF0):
// characters U-00010000 - U-001FFFFF, mask 11110XXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack(
'C*',
$ordVarC,
ord($value[$i + 1]),
ord($value[$i + 2]),
ord($value[$i + 3])
);
$i += 3;
$utf16 = self::utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ordVarC & 0xFC) == 0xF8):
// characters U-00200000 - U-03FFFFFF, mask 111110XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack(
'C*',
$ordVarC,
ord($value[$i + 1]),
ord($value[$i + 2]),
ord($value[$i + 3]),
ord($value[$i + 4])
);
$i += 4;
$utf16 = self::utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ordVarC & 0xFE) == 0xFC):
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack(
'C*',
$ordVarC,
ord($value[$i + 1]),
ord($value[$i + 2]),
ord($value[$i + 3]),
ord($value[$i + 4]),
ord($value[$i + 5])
);
$i += 5;
$utf16 = self::utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
}
}
return $ascii;
}
/**
* Convert a string from one UTF-8 char to one UTF-16 char.
*
* Normally should be handled by mb_convert_encoding, but provides a slower
* PHP-only method for installations that lack the multibyte string
* extension.
*
* This method is from the Solar Framework by Paul M. Jones.
*
* @link http://solarphp.com
* @param string $utf8 UTF-8 character
* @return string UTF-16 character
*/
protected static function utf82utf16($utf8)
{
// Check for mb extension otherwise do by hand.
if (function_exists('mb_convert_encoding')) {
return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
}
switch (strlen($utf8)) {
case 1:
// This case should never be reached, because we are in ASCII range;
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return $utf8;
case 2:
// Return a UTF-16 character from a 2-byte UTF-8 char;
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0x07 & (ord($utf8[0]) >> 2)) . chr((0xC0 & (ord($utf8[0]) << 6)) | (0x3F & ord($utf8[1])));
case 3:
// Return a UTF-16 character from a 3-byte UTF-8 char;
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr((0xF0 & (ord($utf8[0]) << 4))
| (0x0F & (ord($utf8[1]) >> 2))) . chr((0xC0 & (ord($utf8[1]) << 6))
| (0x7F & ord($utf8[2])));
}
// ignoring UTF-32 for now, sorry
return '';
}
}

View File

@@ -1,12 +0,0 @@
<?php
/**
* @see https://github.com/zendframework/zend-json for the canonical source repository
* @copyright Copyright (c) 2005-2018 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-json/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Json\Exception;
class BadMethodCallException extends \BadMethodCallException implements ExceptionInterface
{
}

View File

@@ -1,12 +0,0 @@
<?php
/**
* @see https://github.com/zendframework/zend-json for the canonical source repository
* @copyright Copyright (c) 2005-2018 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-json/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Json\Exception;
interface ExceptionInterface
{
}

View File

@@ -1,12 +0,0 @@
<?php
/**
* @see https://github.com/zendframework/zend-json for the canonical source repository
* @copyright Copyright (c) 2005-2018 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-json/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Json\Exception;
class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface
{
}

View File

@@ -1,12 +0,0 @@
<?php
/**
* @see https://github.com/zendframework/zend-json for the canonical source repository
* @copyright Copyright (c) 2005-2018 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-json/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Json\Exception;
class RecursionException extends RuntimeException
{
}

View File

@@ -1,12 +0,0 @@
<?php
/**
* @see https://github.com/zendframework/zend-json for the canonical source repository
* @copyright Copyright (c) 2005-2018 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-json/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Json\Exception;
class RuntimeException extends \RuntimeException implements ExceptionInterface
{
}

View File

@@ -1,67 +0,0 @@
<?php
/**
* @see https://github.com/zendframework/zend-json for the canonical source repository
* @copyright Copyright (c) 2005-2018 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-json/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Json;
/**
* Encode a string to a native JavaScript expression.
*
* This class simply holds a string with a native JavaScript expression,
* so objects or arrays to be encoded with Zend\Json\Json can contain native
* JavaScript expressions.
*
* Example:
*
* <code>
* $foo = array(
* 'integer' => 9,
* 'string' => 'test string',
* 'function' => Zend\Json\Expr(
* 'function () { window.alert("javascript function encoded by Zend\Json\Json") }'
* ),
* );
*
* echo Zend\Json\Json::encode($foo, false, ['enableJsonExprFinder' => true]);
* </code>
*
* The above returns the following JSON (formatted for readability):
*
* <code>
* {
* "integer": 9,
* "string": "test string",
* "function": function () {window.alert("javascript function encoded by Zend\Json\Json")}
* }
* </code>
*/
class Expr
{
/**
* Storage for javascript expression.
*
* @var string
*/
protected $expression;
/**
* @param string $expression The expression to represent.
*/
public function __construct($expression)
{
$this->expression = (string) $expression;
}
/**
* Cast to string
*
* @return string holded javascript expression.
*/
public function __toString()
{
return $this->expression;
}
}

View File

@@ -1,410 +0,0 @@
<?php
/**
* @see https://github.com/zendframework/zend-json for the canonical source repository
* @copyright Copyright (c) 2005-2018 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-json/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Json;
use SplQueue;
use Zend\Json\Exception\RuntimeException;
/**
* Class for encoding to and decoding from JSON.
*/
class Json
{
/**
* How objects should be encoded: as arrays or as stdClass.
*
* TYPE_ARRAY is 1, which also conveniently evaluates to a boolean true
* value, allowing it to be used with ext/json's functions.
*/
const TYPE_ARRAY = 1;
const TYPE_OBJECT = 0;
/**
* Whether or not to use the built-in PHP functions.
*
* @var bool
*/
public static $useBuiltinEncoderDecoder = false;
/**
* Decodes the given $encodedValue string from JSON.
*
* Uses json_decode() from ext/json if available.
*
* @param string $encodedValue Encoded in JSON format
* @param int $objectDecodeType Optional; flag indicating how to decode
* objects. See {@link Decoder::decode()} for details.
* @return mixed
* @throws RuntimeException
*/
public static function decode($encodedValue, $objectDecodeType = self::TYPE_OBJECT)
{
$encodedValue = (string) $encodedValue;
if (function_exists('json_decode') && static::$useBuiltinEncoderDecoder !== true) {
return self::decodeViaPhpBuiltIn($encodedValue, $objectDecodeType);
}
return Decoder::decode($encodedValue, $objectDecodeType);
}
/**
* Encode the mixed $valueToEncode into the JSON format
*
* Encodes using ext/json's json_encode() if available.
*
* NOTE: Object should not contain cycles; the JSON format
* does not allow object reference.
*
* NOTE: Only public variables will be encoded
*
* NOTE: Encoding native javascript expressions are possible using Zend\Json\Expr.
* You can enable this by setting $options['enableJsonExprFinder'] = true
*
* @see Zend\Json\Expr
*
* @param mixed $valueToEncode
* @param bool $cycleCheck Optional; whether or not to check for object recursion; off by default
* @param array $options Additional options used during encoding
* @return string JSON encoded object
*/
public static function encode($valueToEncode, $cycleCheck = false, array $options = [])
{
if (is_object($valueToEncode)) {
if (method_exists($valueToEncode, 'toJson')) {
return $valueToEncode->toJson();
}
if (method_exists($valueToEncode, 'toArray')) {
return static::encode($valueToEncode->toArray(), $cycleCheck, $options);
}
}
// Pre-process and replace javascript expressions with placeholders
$javascriptExpressions = new SplQueue();
if (isset($options['enableJsonExprFinder'])
&& $options['enableJsonExprFinder'] == true
) {
$valueToEncode = static::recursiveJsonExprFinder($valueToEncode, $javascriptExpressions);
}
// Encoding
$prettyPrint = (isset($options['prettyPrint']) && ($options['prettyPrint'] === true));
$encodedResult = self::encodeValue($valueToEncode, $cycleCheck, $options, $prettyPrint);
// Post-process to revert back any Zend\Json\Expr instances.
$encodedResult = self::injectJavascriptExpressions($encodedResult, $javascriptExpressions);
return $encodedResult;
}
/**
* Discover and replace javascript expressions with temporary placeholders.
*
* Check each value to determine if it is a Zend\Json\Expr; if so, replace the value with
* a magic key and add the javascript expression to the queue.
*
* NOTE this method is recursive.
*
* NOTE: This method is used internally by the encode method.
*
* @see encode
* @param mixed $value a string - object property to be encoded
* @param SplQueue $javascriptExpressions
* @param null|string|int $currentKey
* @return mixed
*/
protected static function recursiveJsonExprFinder(
$value,
SplQueue $javascriptExpressions,
$currentKey = null
) {
if ($value instanceof Expr) {
// TODO: Optimize with ascii keys, if performance is bad
$magicKey = "____" . $currentKey . "_" . (count($javascriptExpressions));
$javascriptExpressions->enqueue([
// If currentKey is integer, encodeUnicodeString call is not required.
'magicKey' => (is_int($currentKey)) ? $magicKey : Encoder::encodeUnicodeString($magicKey),
'value' => $value,
]);
return $magicKey;
}
if (is_array($value)) {
foreach ($value as $k => $v) {
$value[$k] = static::recursiveJsonExprFinder($value[$k], $javascriptExpressions, $k);
}
return $value;
}
if (is_object($value)) {
foreach ($value as $k => $v) {
$value->$k = static::recursiveJsonExprFinder($value->$k, $javascriptExpressions, $k);
}
return $value;
}
return $value;
}
/**
* Pretty-print JSON string
*
* Use 'indent' option to select indentation string; by default, four
* spaces are used.
*
* @param string $json Original JSON string
* @param array $options Encoding options
* @return string
*/
public static function prettyPrint($json, array $options = [])
{
$indentString = isset($options['indent']) ? $options['indent'] : ' ';
$json = trim($json);
$length = strlen($json);
$stack = [];
$result = '';
$inLiteral = false;
for ($i = 0; $i < $length; ++$i) {
switch ($json[$i]) {
case '{':
case '[':
if ($inLiteral) {
break;
}
$stack[] = $json[$i];
$result .= $json[$i];
while (isset($json[$i + 1]) && preg_match('/\s/', $json[$i + 1])) {
++$i;
}
if (isset($json[$i + 1]) && $json[$i + 1] !== '}' && $json[$i + 1] !== ']') {
$result .= "\n" . str_repeat($indentString, count($stack));
}
continue 2;
case '}':
case ']':
if ($inLiteral) {
break;
}
$last = end($stack);
if (($last === '{' && $json[$i] === '}')
|| ($last === '[' && $json[$i] === ']')
) {
array_pop($stack);
}
$result .= $json[$i];
while (isset($json[$i + 1]) && preg_match('/\s/', $json[$i + 1])) {
++$i;
}
if (isset($json[$i + 1]) && ($json[$i + 1] === '}' || $json[$i + 1] === ']')) {
$result .= "\n" . str_repeat($indentString, count($stack) - 1);
}
continue 2;
case '"':
$result .= '"';
if (! $inLiteral) {
$inLiteral = true;
} else {
$backslashes = 0;
$n = $i;
while ($json[--$n] === '\\') {
++$backslashes;
}
if (($backslashes % 2) === 0) {
$inLiteral = false;
while (isset($json[$i + 1]) && preg_match('/\s/', $json[$i + 1])) {
++$i;
}
if (isset($json[$i + 1]) && ($json[$i + 1] === '}' || $json[$i + 1] === ']')) {
$result .= "\n" . str_repeat($indentString, count($stack) - 1);
}
}
}
continue 2;
case ':':
if (! $inLiteral) {
$result .= ': ';
continue 2;
}
break;
case ',':
if (! $inLiteral) {
$result .= ',' . "\n" . str_repeat($indentString, count($stack));
continue 2;
}
break;
default:
if (! $inLiteral && preg_match('/\s/', $json[$i])) {
continue 2;
}
break;
}
$result .= $json[$i];
if ($inLiteral) {
continue;
}
while (isset($json[$i + 1]) && preg_match('/\s/', $json[$i + 1])) {
++$i;
}
if (isset($json[$i + 1]) && ($json[$i + 1] === '}' || $json[$i + 1] === ']')) {
$result .= "\n" . str_repeat($indentString, count($stack) - 1);
}
}
return $result;
}
/**
* Decode a value using the PHP built-in json_decode function.
*
* @param string $encodedValue
* @param int $objectDecodeType
* @return mixed
* @throws RuntimeException
*/
private static function decodeViaPhpBuiltIn($encodedValue, $objectDecodeType)
{
$decoded = json_decode($encodedValue, (bool) $objectDecodeType);
switch (json_last_error()) {
case JSON_ERROR_NONE:
return $decoded;
case JSON_ERROR_DEPTH:
throw new RuntimeException('Decoding failed: Maximum stack depth exceeded');
case JSON_ERROR_CTRL_CHAR:
throw new RuntimeException('Decoding failed: Unexpected control character found');
case JSON_ERROR_SYNTAX:
throw new RuntimeException('Decoding failed: Syntax error');
default:
throw new RuntimeException('Decoding failed');
}
}
/**
* Encode a value to JSON.
*
* Intermediary step between injecting JavaScript expressions.
*
* Delegates to either the PHP built-in json_encode operation, or the
* Encoder component, based on availability of the built-in and/or whether
* or not the component encoder is requested.
*
* @param mixed $valueToEncode
* @param bool $cycleCheck
* @param array $options
* @param bool $prettyPrint
* @return string
*/
private static function encodeValue($valueToEncode, $cycleCheck, array $options, $prettyPrint)
{
if (function_exists('json_encode') && static::$useBuiltinEncoderDecoder !== true) {
return self::encodeViaPhpBuiltIn($valueToEncode, $prettyPrint);
}
return self::encodeViaEncoder($valueToEncode, $cycleCheck, $options, $prettyPrint);
}
/**
* Encode a value to JSON using the PHP built-in json_encode function.
*
* Uses the encoding options:
*
* - JSON_HEX_TAG
* - JSON_HEX_APOS
* - JSON_HEX_QUOT
* - JSON_HEX_AMP
*
* If $prettyPrint is boolean true, also uses JSON_PRETTY_PRINT.
*
* @param mixed $valueToEncode
* @param bool $prettyPrint
* @return string|false Boolean false return value if json_encode is not
* available, or the $useBuiltinEncoderDecoder flag is enabled.
*/
private static function encodeViaPhpBuiltIn($valueToEncode, $prettyPrint = false)
{
if (! function_exists('json_encode') || static::$useBuiltinEncoderDecoder === true) {
return false;
}
$encodeOptions = JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP;
if ($prettyPrint) {
$encodeOptions |= JSON_PRETTY_PRINT;
}
return json_encode($valueToEncode, $encodeOptions);
}
/**
* Encode a value to JSON using the Encoder class.
*
* Passes the value, cycle check flag, and options to Encoder::encode().
*
* Once the result is returned, determines if pretty printing is required,
* and, if so, returns the result of that operation, otherwise returning
* the encoded value.
*
* @param mixed $valueToEncode
* @param bool $cycleCheck
* @param array $options
* @param bool $prettyPrint
* @return string
*/
private static function encodeViaEncoder($valueToEncode, $cycleCheck, array $options, $prettyPrint)
{
$encodedResult = Encoder::encode($valueToEncode, $cycleCheck, $options);
if ($prettyPrint) {
return self::prettyPrint($encodedResult, ['indent' => ' ']);
}
return $encodedResult;
}
/**
* Inject javascript expressions into the encoded value.
*
* Loops through each, substituting the "magicKey" of each with its
* associated value.
*
* @param string $encodedValue
* @param SplQueue $javascriptExpressions
* @return string
*/
private static function injectJavascriptExpressions($encodedValue, SplQueue $javascriptExpressions)
{
foreach ($javascriptExpressions as $expression) {
$encodedValue = str_replace(
sprintf('"%s"', $expression['magicKey']),
$expression['value'],
(string) $encodedValue
);
}
return $encodedValue;
}
}