Skip to content

Commit 7494beb

Browse files
committed
Fixing bug for resource creation
1 parent 4122592 commit 7494beb

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/Http/Message/ResourceCreatedResponse.php

+15
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,19 @@
1313
class ResourceCreatedResponse extends AbstractResponse
1414
{
1515
protected $httpCode = 201;
16+
17+
/**
18+
* @param string $json
19+
*/
20+
public function __construct($json)
21+
{
22+
$data = json_decode($json, true);
23+
24+
if (null !== $data && !empty($data['data']['links']['self'])) {
25+
$data = $data['data']['links']['self'];
26+
$this->headers['Location'] = (!empty($data['href'])) ? $data['href'] : $data;
27+
}
28+
29+
$this->response = self::instance($json, $this->httpCode, $this->headers);
30+
}
1631
}

tests/Http/ResourceCreatedResponseTest.php

+29
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,34 @@
1414

1515
class ResourceCreatedResponseTest extends \PHPUnit_Framework_TestCase
1616
{
17+
18+
public function testResponseWithLocation()
19+
{
20+
$json = json_encode([
21+
"data" =>
22+
[
23+
"type" => "photos",
24+
"id" => "550e8400-e29b-41d4-a716-446655440000",
25+
"attributes" => [
26+
"title" => "Ember Hamster",
27+
"src" => "http://example.com/images/productivity.png"
28+
],
29+
"links" => [
30+
"self" => "http://example.com/photos/550e8400-e29b-41d4-a716-446655440000"
31+
]
32+
]
33+
], JSON_UNESCAPED_SLASHES);
34+
35+
36+
$response = new ResourceCreatedResponse($json);
37+
38+
39+
40+
$this->assertEquals(201, $response->getStatusCode());
41+
$this->assertEquals(['application/vnd.api+json'], $response->getHeader('Content-type'));
42+
$this->assertEquals(['http://example.com/photos/550e8400-e29b-41d4-a716-446655440000'], $response->getHeader('Location'));
43+
}
44+
1745
public function testResponse()
1846
{
1947
$json = json_encode([]);
@@ -22,4 +50,5 @@ public function testResponse()
2250
$this->assertEquals(201, $response->getStatusCode());
2351
$this->assertEquals(['application/vnd.api+json'], $response->getHeader('Content-type'));
2452
}
53+
2554
}

0 commit comments

Comments
 (0)