Completed
Push — master ( f9ded0...b13d5b )
by John
02:58 queued 01:00
created

DefaultHeaderParser   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 1
dl 0
loc 62
rs 10
c 0
b 0
f 0
ccs 29
cts 29
cp 1

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A parse() 0 8 1
B findAcceptableMIMETypes() 0 18 5
A findAPIKey() 0 9 3
A getContentType() 0 9 3
1
<?php
2
namespace LunixREST\APIRequest\HeaderParser;
3
4
class DefaultHeaderParser implements HeaderParser
5
{
6
7
    private $apiKeyHeaderKey;
8
9
    /**
10
     * DefaultHeaderParser constructor.
11
     * @param string $apiKeyHeaderKey
12
     */
13 8
    public function __construct($apiKeyHeaderKey = 'x-api-key')
14
    {
15 8
        $this->apiKeyHeaderKey = $apiKeyHeaderKey;
16 8
    }
17
18 6
    public function parse(array $headers): ParsedHeaders
19
    {
20 6
        $contentType = $this->getContentType($headers);
21 6
        $acceptableMIMETypes = $this->findAcceptableMIMETypes($headers);
22 6
        $apiKey = $this->findAPIKey($headers);
23
24 6
        return new ParsedHeaders($contentType, $acceptableMIMETypes, $apiKey);
25
    }
26
27 6
    protected function findAcceptableMIMETypes(array $headers): array
28
    {
29
        //TODO: follow RFC2616 order
30 6
        $acceptedMIMETypes = [];
31 6
        foreach ($headers as $key => $value) {
32 6
            if (strtolower($key) == 'http-accept') {
33 1
                $values = explode(',', $value);
34 1
                foreach ($values as $acceptedType) {
35 1
                    $typeParts = explode(';', $acceptedType);
36 1
                    if (count($typeParts) > 0) {
37 1
                        $acceptedMIMETypes[] = trim($typeParts[0]);
38
                    }
39
                }
40 6
                break;
41
            }
42
        }
43 6
        return $acceptedMIMETypes;
44
    }
45
46 6
    protected function findAPIKey(array $headers)
47
    {
48 6
        foreach ($headers as $key => $value) {
49 6
            if (strtolower($key) == strtolower($this->apiKeyHeaderKey)) {
50 6
                return $value;
51
            }
52
        }
53 3
        return null;
54
    }
55
56 6
    protected function getContentType(array $headers)
57
    {
58 6
        foreach ($headers as $key => $value) {
59 6
            if (strtolower($key) == 'content-type') {
60 6
                return $value;
61
            }
62
        }
63 4
        return null;
64
    }
65
}
66