Skip to content

Commit

Permalink
show props and optimize getJSON()
Browse files Browse the repository at this point in the history
  • Loading branch information
SmetDenis committed Aug 6, 2016
1 parent 23cdd2d commit 480a087
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@
*/
class Response extends Data
{
/**
* @var null|JSON
*/
protected $_jsonData = null;

/**
* Response constructor.
* @param array|string $data
Expand All @@ -33,6 +38,7 @@ public function __construct($data = array())
$data['code'] = 0;
$data['headers'] = array();
$data['body'] = '';
$this->_jsonData = null;

parent::__construct($data);
}
Expand All @@ -58,6 +64,8 @@ public function getCode()
*/
public function setBody($body)
{
$this->_jsonData = null; // Force update getJSON() result

$this['body'] = (string)$body;
}

Expand All @@ -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;
}

/**
Expand Down
47 changes: 47 additions & 0 deletions tests/ResponseTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php
/**
* JBZoo Http-Client
*
* This file is part of the JBZoo CCK package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @package Http-Client
* @license MIT
* @copyright Copyright (C) JBZoo.com, All rights reserved.
* @link https://github.com/JBZoo/Http-Client
*/

namespace JBZoo\PHPUnit;

use JBZoo\HttpClient\Response;

/**
* Class ResponseTest
* @package JBZoo\PHPUnit
*/
class ResponseTest extends PHPUnit
{
protected $_json = '{"key-1":"value-1","key-2":"value-2"}';

public function testGetSameJSON()
{
$resp = new Response();

$resp->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());
}
}

0 comments on commit 480a087

Please sign in to comment.