Skip to content

Commit

Permalink
Added writeJsonObject method for write JsonSerializable object (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
SiViN authored and Milan Felix Šulc committed Apr 26, 2018
1 parent cd2a907 commit 97e61a7
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 0 deletions.
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
},
"autoload-dev": {
"psr-4": {
"Tests\\Fixtures\\": "tests/fixtures"
}
},
"scripts": {
Expand Down
12 changes: 12 additions & 0 deletions src/Extra/ExtraResponseTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Contributte\Psr7\Psr7Response;
use Contributte\Psr7\Psr7Stream;
use JsonSerializable;

/**
* @method Psr7Stream getBody()
Expand Down Expand Up @@ -54,6 +55,17 @@ public function writeJsonBody(array $data)
->withHeader('Content-Type', 'application/json');
}

/**
* @param JsonSerializable $object
* @return static|Psr7Response
*/
public function writeJsonObject(JsonSerializable $object)
{
return $this
->writeBody(json_encode($object))
->withHeader('Content-Type', 'application/json');
}

/**
* @param bool $assoc
* @return mixed
Expand Down
9 changes: 9 additions & 0 deletions tests/cases/Psr7Response.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use Nette\Application\Responses\TextResponse;
use Nette\Http\IResponse;
use Nette\Http\Response;
use Tester\Assert;
use Tests\Fixtures\JsonObject;

require_once __DIR__ . '/../bootstrap.php';

Expand Down Expand Up @@ -55,6 +56,14 @@ test(function () {
Assert::equal(['foo' => 'bar'], $response->getJsonBody());
});

// writeJsonObject
test(function () {
$response = Psr7ResponseFactory::fromGlobal();
$jsonObject = new JsonObject('bar');
$response = $response->writeJsonObject($jsonObject);
Assert::equal(['foo' => 'bar'], $response->getJsonBody());
});

// appendBody
test(function () {
$response = Psr7ResponseFactory::fromGlobal();
Expand Down
35 changes: 35 additions & 0 deletions tests/fixtures/JsonObject.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace Tests\Fixtures;

use JsonSerializable;

class JsonObject implements JsonSerializable
{

/** @var string */
private $foo;

/**
* JsonObject constructor.
*
* @param string $foo
*/
public function __construct($foo)
{
$this->foo = $foo;
}

/**
* Specify data which should be serialized to JSON
*
* @link http://php.net/manual/en/jsonserializable.jsonserialize.php
* @return mixed data which can be serialized by <b>json_encode</b>, which is a value of any type other than a resource.
* @since 5.4.0
*/
public function jsonSerialize()
{
return ['foo' => $this->foo];
}

}

0 comments on commit 97e61a7

Please sign in to comment.