-
Notifications
You must be signed in to change notification settings - Fork 0
/
ResponseBuilder.php
65 lines (56 loc) · 1.51 KB
/
ResponseBuilder.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
declare(strict_types=1);
namespace Elephox\Http;
use Elephox\Stream\Contract\Stream;
use Elephox\Stream\EmptyStream;
use Elephox\Stream\StringStream;
use JetBrains\PhpStorm\Pure;
use JsonException;
use LogicException;
use Elephox\Mimey\MimeType;
use Elephox\Mimey\MimeTypeInterface;
/**
* @psalm-consistent-constructor
*/
class ResponseBuilder extends AbstractMessageBuilder implements Contract\ResponseBuilder
{
#[Pure]
public function __construct(
?string $protocolVersion = null,
?Contract\HeaderMap $headers = null,
?Stream $body = null,
protected ?ResponseCode $responseCode = null,
protected ?MimeTypeInterface $mimeType = null
) {
parent::__construct($protocolVersion, $headers, $body);
}
public function responseCode(ResponseCode $responseCode): static
{
$this->responseCode = $responseCode;
return $this;
}
public function contentType(?MimeTypeInterface $mimeType): static
{
$this->mimeType = $mimeType;
return $this;
}
/**
* @throws JsonException
*/
public function jsonBody(array $data): static
{
$json = json_encode($data, JSON_THROW_ON_ERROR);
$jsonStream = new StringStream($json);
return $this->body($jsonStream)->contentType(MimeType::ApplicationJson);
}
public function get(): Contract\Response
{
return new Response(
$this->protocolVersion ?? self::DefaultProtocolVersion,
$this->headers ?? new HeaderMap(),
$this->body ?? new EmptyStream(),
$this->responseCode ?? throw new LogicException('Response code is not set.'),
$this->mimeType
);
}
}