|
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
|
|
|
|