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

DefaultHeaderParser   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

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

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A parse() 0 7 1
B findAcceptableMIMETypes() 0 17 5
A findAPIKey() 0 8 3
A getContentType() 0 8 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