Completed
Push — master ( 005b00...a8a0a1 )
by John
01:59
created

DefaultHeaderParser::findAPIKey()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

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