|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace WebServCo\Framework\Helpers\Http; |
|
6
|
|
|
|
|
7
|
|
|
class HeadersHelper |
|
8
|
|
|
{ |
|
9
|
|
|
/** |
|
10
|
|
|
* Convert headers array (one header per line) into parsed array |
|
11
|
|
|
* |
|
12
|
|
|
* Array key will contain the header name |
|
13
|
|
|
* Array value will be an array containing all the header values. |
|
14
|
|
|
* "HTTP" line is ignored. |
|
15
|
|
|
* |
|
16
|
|
|
* @param array<int,string> $responseHeadersArray |
|
17
|
|
|
* @return array<string,mixed> |
|
18
|
|
|
*/ |
|
19
|
|
|
public static function parseArray(array $responseHeadersArray = [], bool $lowercaseKey = true): array |
|
20
|
|
|
{ |
|
21
|
|
|
$headers = []; |
|
22
|
|
|
|
|
23
|
|
|
foreach ($responseHeadersArray as $index => $line) { |
|
24
|
|
|
if ('HTTP' === \substr($line, 0, 4)) { |
|
25
|
|
|
continue; /* we'll get the status code elsewhere */ |
|
26
|
|
|
} |
|
27
|
|
|
$parts = \explode(': ', $line, 2); |
|
28
|
|
|
if (!isset($parts[1])) { |
|
29
|
|
|
continue; // invalid header (missing colon) |
|
30
|
|
|
} |
|
31
|
|
|
[$key, $value] = $parts; |
|
32
|
|
|
if ($lowercaseKey) { |
|
33
|
|
|
$key = \strtolower($key); |
|
34
|
|
|
} |
|
35
|
|
|
if (isset($headers[$key])) { |
|
36
|
|
|
if (!\is_array($headers[$key])) { |
|
37
|
|
|
$headers[$key] = [$headers[$key]]; |
|
38
|
|
|
} |
|
39
|
|
|
// check cookies |
|
40
|
|
|
if ('Set-Cookie' === $key) { |
|
41
|
|
|
$parts = \explode('=', $value, 2); |
|
42
|
|
|
$cookieName = $parts[0]; |
|
43
|
|
|
if (\is_array($headers[$key])) { |
|
44
|
|
|
foreach ($headers[$key] as $cookieIndex => $existingCookie) { |
|
45
|
|
|
// check if we already have a cookie with the same name |
|
46
|
|
|
if (0 !== \mb_stripos($existingCookie, $cookieName)) { |
|
47
|
|
|
continue; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
// remove previous cookie with the same name |
|
51
|
|
|
unset($headers[$key][$cookieIndex]); |
|
52
|
|
|
} |
|
53
|
|
|
} |
|
54
|
|
|
} |
|
55
|
|
|
$headers[$key][] = \trim($value); |
|
56
|
|
|
$headers[$key] = \array_values((array) $headers[$key]); // re-index array |
|
57
|
|
|
} else { |
|
58
|
|
|
$headers[$key][] = \trim($value); |
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
|
|
return $headers; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
/** |
|
65
|
|
|
* Convert headers string to array. |
|
66
|
|
|
* |
|
67
|
|
|
* Does not support multi line headers. |
|
68
|
|
|
* "HTTP" line is ignored. |
|
69
|
|
|
* |
|
70
|
|
|
* @return array<string,mixed> |
|
71
|
|
|
*/ |
|
72
|
|
|
public static function parseString(string $headers, bool $lowercaseKey = true): array |
|
73
|
|
|
{ |
|
74
|
|
|
$array = \explode(\PHP_EOL, $headers); |
|
75
|
|
|
return self::parseArray($array, $lowercaseKey); |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|