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