HeadersNegotiator::getAllowedHeaders()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chubbyphp\Cors\Negotiation;
6
7
use Psr\Http\Message\ServerRequestInterface;
8
9
final class HeadersNegotiator implements HeadersNegotiatorInterface
10
{
11
    /**
12
     * @var array<string>
13
     */
14
    private $allowHeaders;
15
16
    /**
17
     * @param array<string> $allowHeaders
18
     */
19 6
    public function __construct(array $allowHeaders)
20
    {
21 6
        $this->allowHeaders = [];
22 6
        foreach ($allowHeaders as $allowHeader) {
23 6
            $this->addAllowHeader($allowHeader);
24
        }
25 6
    }
26
27 5
    public function negotiate(ServerRequestInterface $request): bool
28
    {
29 5
        if (!$request->hasHeader(self::HEADER)) {
30 1
            return false;
31
        }
32
33 4
        $headers = $this->getHeaders($request);
34 4
        foreach ($headers as $i => $header) {
35 4
            foreach ($this->allowHeaders as $allowHeader) {
36 4
                if (strtolower($allowHeader) !== strtolower($header)) {
37 4
                    continue;
38
                }
39
40 4
                unset($headers[$i]);
41
            }
42
        }
43
44 4
        return [] === $headers;
45
    }
46
47
    /**
48
     * @return array<string>
49
     */
50 1
    public function getAllowedHeaders(): array
51
    {
52 1
        return $this->allowHeaders;
53
    }
54
55 6
    private function addAllowHeader(string $allowHeader): void
56
    {
57 6
        $this->allowHeaders[] = $allowHeader;
58 6
    }
59
60
    /**
61
     * @return array<string>
62
     */
63
    private function getHeaders(ServerRequestInterface $request): array
64
    {
65 4
        $headers = [];
66
        foreach (explode(',', $request->getHeaderLine(self::HEADER)) as $header) {
67 4
            $headers[] = trim($header);
68 4
        }
69 4
70
        return $headers;
71
    }
72
}
73