HttpStatus::setDb()   A
last analyzed

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 1
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
    /**
13
     * @var string
14
     */
15
    private const FILENAME = __DIR__ . '/../data/http-status.php';
16
17
    private array $db;
18
19
    private int   $statusCode;
20
21 84
    public function __construct(int $statusCode)
22
    {
23 84
        $db = (array) include self::FILENAME;
24 84
        $this->setDb($db);
25 84
        $this->validateStatusCode($statusCode);
26 82
        $this->setStatusCode($statusCode);
27
    }
28
29 82
    public function get(): Entity
30
    {
31 82
        $db         = $this->getDb();
32 82
        $statusCode = $this->getStatusCode();
33
34 82
        $entity             = new Entity();
35 82
        $entity->statusCode = $statusCode;
36 82
        $entity->name       = $db[$entity->statusCode]['name'];
37 82
        $entity->phrase     = $db[$entity->statusCode]['phrase'];
38 82
        $entity->exception  = $db[$entity->statusCode]['exception'];
39 82
        $entity->url        = sprintf('https://httpstatuses.com/%s', $entity->statusCode);
40
41 82
        return $entity;
42
    }
43
44 84
    private function getDb(): array
45
    {
46 84
        return $this->db;
47
    }
48
49 84
    private function setDb(array $db): self
50
    {
51 84
        $this->db = $db;
52
53 84
        return $this;
54
    }
55
56 82
    private function getStatusCode(): int
57
    {
58 82
        return $this->statusCode;
59
    }
60
61 82
    private function setStatusCode(int $statusCode): self
62
    {
63 82
        $this->statusCode = $statusCode;
64
65 82
        return $this;
66
    }
67
68 84
    private function validateStatusCode(int $statusCode): self
69
    {
70 84
        if (!array_key_exists($statusCode, $this->getDb())) {
71 2
            $format  = 'The status code %d is not supported';
72 2
            $message = sprintf($format, $statusCode);
73 2
            throw new InvalidArgumentException($message);
74
        }
75
76 82
        return $this;
77
    }
78
}
79