Completed
Push — master ( 21e2dd...2fbabb )
by Dominik
02:22 queued 20s
created

HeadersNegotiator::negotiate()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 12
cts 12
cp 1
rs 8.9297
c 0
b 0
f 0
cc 6
nc 9
nop 1
crap 6
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 string[]
13
     */
14
    private $allowHeaders;
15
16
    /**
17
     * @param 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
    /**
28
     * @param string $allowHeader
29
     */
30 6
    private function addAllowHeader(string $allowHeader): void
31
    {
32 6
        $this->allowHeaders[] = $allowHeader;
33 6
    }
34
35
    /**
36
     * @param ServerRequestInterface $request
37
     *
38
     * @return bool
39
     */
40 5
    public function negotiate(ServerRequestInterface $request): bool
41
    {
42 5
        if (!$request->hasHeader(self::HEADER)) {
43 1
            return false;
44
        }
45
46 4
        $headers = [];
47 4
        foreach (explode(',', $request->getHeaderLine(self::HEADER)) as $header) {
48 4
            $headers[] = trim($header);
49
        }
50
51 4
        foreach ($headers as $i => $header) {
52 4
            foreach ($this->allowHeaders as $allowHeader) {
53 4
                if (mb_strtolower($allowHeader) !== mb_strtolower($header)) {
54 4
                    continue;
55
                }
56
57 4
                unset($headers[$i]);
58
            }
59
        }
60
61 4
        return [] === $headers;
62
    }
63
64
    /**
65
     * @return string[]
66
     */
67 1
    public function getAllowedHeaders(): array
68
    {
69 1
        return $this->allowHeaders;
70
    }
71
}
72