Test Failed
Branch master (f83914)
by Rasul
07:02
created

HeadersCollection::get()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 7
nc 4
nop 0
dl 0
loc 14
rs 9.6111
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Furious\Psr7\Header;
6
7
final class HeadersCollection
8
{
9
    private array $serverParameters;
1 ignored issue
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_ARRAY, expecting T_FUNCTION or T_CONST
Loading history...
10
11
    /**
12
     * HeadersCollection constructor.
13
     * @param array $serverParameters
14
     */
15
    public function __construct(array $serverParameters)
16
    {
17
        $this->serverParameters = $serverParameters;
18
    }
19
20
    public function get(): array
21
    {
22
        $headers = [];
23
        foreach ($this->serverParameters as $key => $value) {
24
            if (!is_string($key) or $value === '') {
25
                continue;
26
            }
27
28
            if ($name = $this->getHeaderName($key)) {
29
                $headers[$name] = $value;
30
            }
31
        }
32
33
        return $headers;
34
    }
35
36
    private function getHeaderName(string $key): ?string
37
    {
38
        $name = null;
39
40
        if ($this->isRedirectHeader($key)) {
41
            $key = substr($key, 9);
42
        }
43
44
        if ($this->isContentHeader($key)) {
45
            $name = strtr(strtolower($key), '_', '-');
46
        }
47
48
        if ($this->isHttpHeader($key)) {
49
            $name = strtr(strtolower(substr($key, 5)), '_', '-');
50
        }
51
52
        return $name;
53
    }
54
55
    private function isRedirectHeader(string $key): bool
56
    {
57
        return strpos($key, 'REDIRECT_') === 0;
58
    }
59
60
    private function isContentHeader(string $key): bool
61
    {
62
        return strpos($key, 'CONTENT_') === 0;
63
    }
64
65
    private function isHttpHeader(string $key): bool
66
    {
67
        return strpos($key, 'HTTP_') === 0;
68
    }
69
}