1
|
|
|
<?php
|
2
|
|
|
|
3
|
|
|
namespace MarcolaMr\Router;
|
4
|
|
|
|
5
|
|
|
class Response
|
6
|
|
|
{
|
7
|
|
|
/** @var string */
|
8
|
|
|
private int $httpCode = 200;
|
9
|
|
|
|
10
|
|
|
/** @var array */
|
11
|
|
|
private array $headers = [];
|
12
|
|
|
|
13
|
|
|
/** @var string */
|
14
|
|
|
private string $contentType = "text/html";
|
15
|
|
|
|
16
|
|
|
/** @var mixed */
|
17
|
|
|
private $content;
|
18
|
|
|
|
19
|
|
|
/**
|
20
|
|
|
* Construtor da classe
|
21
|
|
|
*
|
22
|
|
|
* @param integer $httpCode
|
23
|
|
|
* @param mixed $content
|
24
|
|
|
* @param string $contentType
|
25
|
|
|
*/
|
26
|
|
|
public function __construct(int $httpCode, $content, string $contentType = "text/html")
|
27
|
|
|
{
|
28
|
|
|
$this->httpCode = $httpCode;
|
29
|
|
|
$this->content = $content;
|
30
|
|
|
$this->setContentType($contentType);
|
31
|
|
|
}
|
32
|
|
|
|
33
|
|
|
/**
|
34
|
|
|
* Método responsável por enviar a resposta para o usuário
|
35
|
|
|
*
|
36
|
|
|
* @return void
|
37
|
|
|
*/
|
38
|
|
|
public function sendResponse(): void
|
39
|
|
|
{
|
40
|
|
|
$this->sendHeaders();
|
41
|
|
|
|
42
|
|
|
switch ($this->contentType) {
|
43
|
|
|
case 'text/html':
|
44
|
|
|
echo $this->content;
|
45
|
|
|
exit;
|
|
|
|
|
46
|
|
|
}
|
47
|
|
|
}
|
48
|
|
|
|
49
|
|
|
/**
|
50
|
|
|
* Método responsável por alterar o content type do response
|
51
|
|
|
*
|
52
|
|
|
* @param string $contentType
|
53
|
|
|
* @return void
|
54
|
|
|
*/
|
55
|
|
|
private function setContentType(string $contentType): void
|
56
|
|
|
{
|
57
|
|
|
$this->contentType = $contentType;
|
58
|
|
|
$this->addHeader("Content-Type", $contentType);
|
59
|
|
|
}
|
60
|
|
|
|
61
|
|
|
/**
|
62
|
|
|
* Método responsável or adicionar um registro no cabeçalho do response
|
63
|
|
|
*
|
64
|
|
|
* @param string $key
|
65
|
|
|
* @param string $value
|
66
|
|
|
* @return void
|
67
|
|
|
*/
|
68
|
|
|
private function addHeader(string $key, string $value): void
|
69
|
|
|
{
|
70
|
|
|
$this->headers[$key] = $value;
|
71
|
|
|
}
|
72
|
|
|
|
73
|
|
|
/**
|
74
|
|
|
* Método responsável por enviar a resposta para o navegador
|
75
|
|
|
*
|
76
|
|
|
* @return void
|
77
|
|
|
*/
|
78
|
|
|
private function sendHeaders(): void
|
79
|
|
|
{
|
80
|
|
|
http_response_code($this->httpCode);
|
81
|
|
|
|
82
|
|
|
foreach ($this->headers as $key => $value) {
|
83
|
|
|
header($key . ": " . $value);
|
84
|
|
|
}
|
85
|
|
|
}
|
86
|
|
|
}
|
87
|
|
|
|
In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.