Completed
Pull Request — master (#1)
by Dominik
01:48
created

HeadersNegotiator   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 0
dl 0
loc 57
ccs 19
cts 19
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 2
A addAllowHeader() 0 4 1
A negotiate() 0 17 5
A getAllowedHeaders() 0 4 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 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 = $request->getHeader(self::HEADER);
47 4
        foreach ($headers as $i => $header) {
48 4
            foreach ($this->allowHeaders as $allowHeader) {
49 4
                if (mb_strtolower($allowHeader) === mb_strtolower($header)) {
50 4
                    unset($headers[$i]);
51
                }
52
            }
53
        }
54
55 4
        return [] === $headers;
56
    }
57
58
    /**
59
     * @return string[]
60
     */
61 1
    public function getAllowedHeaders(): array
62
    {
63 1
        return $this->allowHeaders;
64
    }
65
}
66