-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathResponse.php
More file actions
87 lines (72 loc) · 2.29 KB
/
Response.php
File metadata and controls
87 lines (72 loc) · 2.29 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
declare(strict_types=1);
namespace Phenix\Http;
use Amp\ByteStream\ReadableStream;
use Amp\Http\Server\Response as ServerResponse;
use Amp\Http\Server\Trailers;
use Phenix\Contracts\Arrayable;
use Phenix\Facades\View;
use Phenix\Http\Constants\HttpStatus;
class Response
{
protected ReadableStream|string $body;
protected HttpStatus $status;
protected array $headers;
protected Trailers|null $trailers;
public function __construct()
{
$this->body = '';
$this->status = HttpStatus::OK;
$this->trailers = null;
}
public function plain(string $content, HttpStatus $status = HttpStatus::OK, array $headers = []): self
{
$this->body = $content;
$this->status = $status;
$this->headers = [...['content-type' => 'text/plain'], ...$headers];
return $this;
}
/**
* @param Arrayable|array<string|int, array|string|int|bool> $content
*/
public function json(
Arrayable|array $content = [],
HttpStatus $status = HttpStatus::OK,
array $headers = []
): self {
if ($content instanceof Arrayable) {
$content = $content->toArray();
}
$this->body = json_encode($content);
$this->status = $status;
$this->headers = [...['content-type' => 'application/json'], ...$headers];
return $this;
}
public function view(
string $template,
array $data = [],
HttpStatus $status = HttpStatus::OK,
array $headers = []
): self {
$this->body = View::view($template, $data)->render();
$this->status = $status;
$this->headers = [...['content-type' => 'text/html; charset=utf-8'], ...$headers];
return $this;
}
public function redirect(string $location, HttpStatus $status = HttpStatus::FOUND, array $headers = []): self
{
$this->body = json_encode(['redirectTo' => $location]);
$this->status = $status;
$this->headers = [...['Location' => $location, 'content-type' => 'application/json'], ...$headers];
return $this;
}
public function send(): ServerResponse
{
return new ServerResponse(
$this->status->value,
$this->headers,
$this->body,
$this->trailers
);
}
}