1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* (c) Markus Lanthaler <[email protected]> |
5
|
|
|
* |
6
|
|
|
* For the full copyright and license information, please view the LICENSE |
7
|
|
|
* file that was distributed with this source code. |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
namespace ML\FgcClient; |
11
|
|
|
|
12
|
|
|
use Psr\Http\Message\ResponseInterface; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* HTTP response headers parser |
16
|
|
|
* |
17
|
|
|
* More or less a shameless copy of {@link https://github.com/php-http/curl-client curl-client's} |
18
|
|
|
* {@code HeadersParser}. |
19
|
|
|
* |
20
|
|
|
* @author Markus Lanthaler <[email protected]> |
21
|
|
|
*/ |
22
|
|
|
class HeaderParser |
23
|
|
|
{ |
24
|
|
|
/** |
25
|
|
|
* Parse headers and write them to response object. |
26
|
|
|
* |
27
|
|
|
* @param string[] $headers Response headers as array of header lines. |
28
|
|
|
* @param ResponseInterface $response Response to write headers to. |
29
|
|
|
* |
30
|
|
|
* @return ResponseInterface |
31
|
|
|
* |
32
|
|
|
* @throws \InvalidArgumentException For invalid status code arguments. |
33
|
|
|
* @throws \RuntimeException |
34
|
|
|
*/ |
35
|
52 |
|
public function parseArray(array $headers, ResponseInterface $response) |
36
|
|
|
{ |
37
|
52 |
|
$statusLine = trim(array_shift($headers)); |
38
|
52 |
|
$parts = explode(' ', $statusLine, 3); |
39
|
52 |
|
if (count($parts) < 2 || substr(strtolower($parts[0]), 0, 5) !== 'http/') { |
40
|
|
|
throw new \RuntimeException( |
41
|
|
|
sprintf('"%s" is not a valid HTTP status line', $statusLine) |
42
|
|
|
); |
43
|
|
|
} |
44
|
|
|
|
45
|
52 |
|
$reasonPhrase = count($parts) > 2 ? $parts[2] : ''; |
46
|
|
|
$response = $response |
47
|
52 |
|
->withStatus((int) $parts[1], $reasonPhrase) |
48
|
52 |
|
->withProtocolVersion(substr($parts[0], 5)); |
49
|
|
|
|
50
|
52 |
|
foreach ($headers as $headerLine) { |
51
|
52 |
|
$headerLine = trim($headerLine); |
52
|
52 |
|
if ('' === $headerLine) { |
53
|
|
|
continue; |
54
|
|
|
} |
55
|
|
|
|
56
|
52 |
|
$parts = explode(':', $headerLine, 2); |
57
|
52 |
|
if (count($parts) !== 2) { |
58
|
|
|
throw new \RuntimeException( |
59
|
|
|
sprintf('"%s" is not a valid HTTP header line', $headerLine) |
60
|
|
|
); |
61
|
|
|
} |
62
|
52 |
|
$name = trim(urldecode($parts[0])); |
63
|
52 |
|
$value = trim(urldecode($parts[1])); |
64
|
52 |
|
if ($response->hasHeader($name)) { |
65
|
|
|
$response = $response->withAddedHeader($name, $value); |
66
|
|
|
} else { |
67
|
52 |
|
$response = $response->withHeader($name, $value); |
68
|
|
|
} |
69
|
52 |
|
} |
70
|
|
|
|
71
|
52 |
|
return $response; |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|