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
![]() |
|||
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 |