HeadersNegotiator   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 20
c 2
b 1
f 0
dl 0
loc 62
ccs 24
cts 24
cp 1
rs 10
wmc 11

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 2
A negotiate() 0 18 5
A getAllowedHeaders() 0 3 1
A getHeaders() 0 8 2
A addAllowHeader() 0 3 1
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