diff --git a/src/Response.php b/src/Response.php index 6cc11db..71d73b5 100644 --- a/src/Response.php +++ b/src/Response.php @@ -24,6 +24,11 @@ */ class Response extends Data { + /** + * @var null|JSON + */ + protected $_jsonData = null; + /** * Response constructor. * @param array|string $data @@ -33,6 +38,7 @@ public function __construct($data = array()) $data['code'] = 0; $data['headers'] = array(); $data['body'] = ''; + $this->_jsonData = null; parent::__construct($data); } @@ -58,6 +64,8 @@ public function getCode() */ public function setBody($body) { + $this->_jsonData = null; // Force update getJSON() result + $this['body'] = (string)$body; } @@ -74,7 +82,12 @@ public function getBody() */ public function getJSON() { - return new JSON($this->getBody()); + if (null === $this->_jsonData) { + $this->_jsonData = new JSON($this->get('body')); + $this->_jsonData->setFlags(\ArrayObject::ARRAY_AS_PROPS); // For JBZoo/Data less 1.4.2 + } + + return $this->_jsonData; } /** diff --git a/tests/ResponseTest.php b/tests/ResponseTest.php new file mode 100644 index 0000000..cc32fe9 --- /dev/null +++ b/tests/ResponseTest.php @@ -0,0 +1,47 @@ +setBody($this->_json); + + $json1 = $resp->getJSON(); + $json2 = $resp->getJSON(); + + isSame('value-1', $resp->getJSON()->get('key-1')); + isSame('value-2', $resp->getJSON()->find('key-2')); + isSame($json1, $json2); + isSame($json1, $resp->getJSON()); + isSame($json2, $resp->getJSON()); + + $resp->setBody($this->_json); + isNotSame($json1, $resp->getJSON()); + isNotSame($json2, $resp->getJSON()); + isSame($resp->getJSON(), $resp->getJSON()); + } +}