Skip to content

Commit d25bc44

Browse files
authored
feat(response): add a new Response class for json responses (#1423)
Signed-off-by: Tonko Mulder <[email protected]>
1 parent 15c303e commit d25bc44

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Tempest\Http\Responses;
6+
7+
use Tempest\Http\Header;
8+
use Tempest\Http\IsResponse;
9+
use Tempest\Http\Response;
10+
use Tempest\Http\Status;
11+
12+
final class Json implements Response
13+
{
14+
use IsResponse;
15+
16+
public function __construct(?array $body = null)
17+
{
18+
$this->status = Status::OK;
19+
$this->body = $body;
20+
$this->addHeader('Accept', 'application/json');
21+
$this->addHeader('Content-Type', 'application/json');
22+
}
23+
}

packages/http/tests/Responses/CreatedResponseTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@
55
namespace Tempest\Http\Tests\Responses;
66

77
use PHPUnit\Framework\TestCase;
8+
use Tempest\Http\Header;
89
use Tempest\Http\Responses\Created;
10+
use Tempest\Http\Responses\Json;
911
use Tempest\Http\Status;
1012

1113
/**
@@ -22,4 +24,20 @@ public function test_created_response(): void
2224
$this->assertSame('{"foo":"bar"}', $response->body);
2325
$this->assertNotSame(Status::OK, $response->status);
2426
}
27+
28+
public function test_json_response(): void
29+
{
30+
$response = new Json(['foo' => 'bar']);
31+
32+
$this->assertSame(Status::OK, $response->status);
33+
$this->assertSame(['foo' => 'bar'], $response->body);
34+
35+
$accept = $response->getHeader('Accept');
36+
$contentType = $response->getHeader('Content-Type');
37+
38+
$this->assertSame('Accept', $accept->name);
39+
$this->assertSame('application/json', $accept->values[0]);
40+
$this->assertSame('Content-Type', $contentType->name);
41+
$this->assertSame('application/json', $contentType->values[0]);
42+
}
2543
}

0 commit comments

Comments
 (0)