StatusCodeManager   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 10
eloc 29
c 2
b 1
f 0
dl 0
loc 61
ccs 27
cts 27
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 13 5
A makeStatusCode() 0 27 5
1
<?php
2
3
namespace HttpStatusCodes;
4
5
use ReflectionClass;
6
7
class StatusCodeManager
8
{
9
    protected $statusCodesClass;
10
11
    /** @var array */
12
    protected $statusWithConstantsName;
13
14
    /**
15
     * StatusCodeManager constructor.
16
     * @param $statusCodesClass
17
     * @throws \ReflectionException
18
     */
19 9
    public function __construct(string $statusCodesClass = null)
20
    {
21 9
        if ($statusCodesClass) {
22 4
            $this->statusCodesClass = $statusCodesClass;
23
        } else {
24 5
            $this->statusCodesClass = new RFCStatusCodes();
25
        }
26
27 9
        $rc                            = new ReflectionClass($this->statusCodesClass);
28 9
        $this->statusWithConstantsName = [];
29 9
        foreach ($rc->getConstants() as $constantName => $code) {
30 9
            if (is_int($code) && substr($constantName, 0, 5) === 'HTTP_') {
31 9
                $this->statusWithConstantsName[$code] = $constantName;
32
            }
33
        }
34
    }
35
36
    /**
37
     * @param string|int $code
38
     * @return StatusCode|null
39
     * @throws \ReflectionException
40
     */
41 9
    public function makeStatusCode($code): ?StatusCode
42
    {
43 9
        if (is_int($code)) {
44 6
            if (!isset($this->statusWithConstantsName[$code])) {
45 2
                return null;
46
            }
47 4
            $code = $this->statusWithConstantsName[$code];
48
        }
49
50 7
        $rc           = new ReflectionClass($this->statusCodesClass);
51 7
        $constantInfo = $rc->getReflectionConstant($code);
52 7
        if (!$constantInfo) {
0 ignored issues
show
introduced by
$constantInfo is of type ReflectionClassConstant, thus it always evaluated to true.
Loading history...
53 1
            return null;
54
        }
55 6
        preg_match_all('#@(.*?)( )(.*?)?\n#s', $constantInfo->getDocComment(), $annotations);
56 6
        $filteredAnnotation = array_combine($annotations[1], $annotations[3]);
57
58 6
        $filteredAnnotation['code'] = $constantInfo->getValue();
59
60 6
        if (!isset($filteredAnnotation['message'])) {
61 1
            $text                          = str_replace('HTTP_', '', $code);
62 1
            $text                          = strtolower($text);
63 1
            $text                          = str_replace('_', '_', $text);
64 1
            $filteredAnnotation['message'] = ucwords($text);
65
        }
66
67 6
        return new StatusCode($filteredAnnotation);
68
    }
69
}
70