1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Ctw\Http; |
5
|
|
|
|
6
|
|
|
use Ctw\Http\Entity\HttpStatus as Entity; |
7
|
|
|
use Ctw\Http\Exception\InvalidArgumentException; |
8
|
|
|
use Fig\Http\Message\StatusCodeInterface; |
9
|
|
|
|
10
|
|
|
class HttpStatus implements StatusCodeInterface |
11
|
|
|
{ |
12
|
|
|
private const FILENAME = __DIR__ . '/../data/http-status.php'; |
13
|
|
|
|
14
|
|
|
private array $db; |
15
|
|
|
|
16
|
|
|
private int $statusCode; |
17
|
|
|
|
18
|
84 |
|
public function __construct(int $statusCode) |
19
|
|
|
{ |
20
|
84 |
|
$db = (array) include self::FILENAME; |
21
|
84 |
|
$this->setDb($db); |
22
|
84 |
|
$this->validateStatusCode($statusCode); |
23
|
82 |
|
$this->setStatusCode($statusCode); |
24
|
82 |
|
} |
25
|
|
|
|
26
|
82 |
|
public function get(): Entity |
27
|
|
|
{ |
28
|
82 |
|
$db = $this->getDb(); |
29
|
82 |
|
$statusCode = $this->getStatusCode(); |
30
|
|
|
|
31
|
82 |
|
$entity = new Entity(); |
32
|
82 |
|
$entity->statusCode = $statusCode; |
33
|
82 |
|
$entity->name = $db[$entity->statusCode]['name']; |
34
|
82 |
|
$entity->phrase = $db[$entity->statusCode]['phrase']; |
35
|
82 |
|
$entity->exception = $db[$entity->statusCode]['exception']; |
36
|
82 |
|
$entity->url = sprintf('https://httpstatuses.com/%s', $entity->statusCode); |
37
|
|
|
|
38
|
82 |
|
return $entity; |
39
|
|
|
} |
40
|
|
|
|
41
|
84 |
|
private function getDb(): array |
42
|
|
|
{ |
43
|
84 |
|
return $this->db; |
44
|
|
|
} |
45
|
|
|
|
46
|
84 |
|
private function setDb(array $db): self |
47
|
|
|
{ |
48
|
84 |
|
$this->db = $db; |
49
|
|
|
|
50
|
84 |
|
return $this; |
51
|
|
|
} |
52
|
|
|
|
53
|
82 |
|
private function getStatusCode(): int |
54
|
|
|
{ |
55
|
82 |
|
return $this->statusCode; |
56
|
|
|
} |
57
|
|
|
|
58
|
82 |
|
private function setStatusCode(int $statusCode): self |
59
|
|
|
{ |
60
|
82 |
|
$this->statusCode = $statusCode; |
61
|
|
|
|
62
|
82 |
|
return $this; |
63
|
|
|
} |
64
|
|
|
|
65
|
84 |
|
private function validateStatusCode(int $statusCode): self |
66
|
|
|
{ |
67
|
84 |
|
if (!in_array($statusCode, array_keys($this->getDb()), true)) { |
68
|
2 |
|
$format = 'The status code %d is not supported'; |
69
|
2 |
|
$message = sprintf($format, $statusCode); |
70
|
2 |
|
throw new InvalidArgumentException($message); |
71
|
|
|
} |
72
|
|
|
|
73
|
82 |
|
return $this; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|