Passed
Push — master ( d411b0...ce24d5 )
by Jonathan
02:51
created

HttpStatus::throwException()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 5
c 0
b 0
f 0
ccs 3
cts 3
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
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