| 1 |
<?php |
| 2 |
|
| 3 |
namespace YoastSEO_Vendor\GuzzleHttp\Handler; |
| 4 |
|
| 5 |
use YoastSEO_Vendor\GuzzleHttp\Utils; |
| 6 |
/** |
| 7 |
* @internal |
| 8 |
*/ |
| 9 |
final class HeaderProcessor |
| 10 |
{ |
| 11 |
/** |
| 12 |
* Returns the HTTP version, status code, reason phrase, and headers. |
| 13 |
* |
| 14 |
* @param string[] $headers |
| 15 |
* |
| 16 |
* @return array{0:string, 1:int, 2:?string, 3:array} |
| 17 |
* |
| 18 |
* @throws \RuntimeException |
| 19 |
*/ |
| 20 |
public static function parseHeaders(array $headers) : array |
| 21 |
{ |
| 22 |
if ($headers === []) { |
| 23 |
throw new \RuntimeException('Expected a non-empty array of header data'); |
| 24 |
} |
| 25 |
$headers = self::getLastHeaderBlock(\array_values($headers)); |
| 26 |
$statusLine = \array_shift($headers); |
| 27 |
if ($statusLine === null) { |
| 28 |
throw new \RuntimeException('Expected a non-empty array of header data'); |
| 29 |
} |
| 30 |
$parts = \explode(' ', $statusLine, 3); |
| 31 |
$version = \explode('/', $parts[0])[1] ?? null; |
| 32 |
if ($version === null) { |
| 33 |
throw new \RuntimeException('HTTP version missing from header data'); |
| 34 |
} |
| 35 |
$status = $parts[1] ?? null; |
| 36 |
if ($status === null) { |
| 37 |
throw new \RuntimeException('HTTP status code missing from header data'); |
| 38 |
} |
| 39 |
if (!\preg_match('/^\\d{3}$/', $status)) { |
| 40 |
throw new \RuntimeException('HTTP status code is invalid'); |
| 41 |
} |
| 42 |
foreach ($headers as $header) { |
| 43 |
if (\strpos($header, ':') === \false) { |
| 44 |
throw new \RuntimeException('HTTP header line is invalid'); |
| 45 |
} |
| 46 |
} |
| 47 |
return [$version, (int) $status, $parts[2] ?? null, \YoastSEO_Vendor\GuzzleHttp\Utils::headersFromLines($headers)]; |
| 48 |
} |
| 49 |
/** |
| 50 |
* @param non-empty-list<string> $headers |
| 51 |
* |
| 52 |
* @return list<string> |
| 53 |
*/ |
| 54 |
private static function getLastHeaderBlock(array $headers) : array |
| 55 |
{ |
| 56 |
$lastStatusLine = 0; |
| 57 |
foreach ($headers as $index => $line) { |
| 58 |
if (\preg_match('/^HTTP\\/\\S+\\s+/i', $line)) { |
| 59 |
$lastStatusLine = $index; |
| 60 |
} |
| 61 |
} |
| 62 |
return \array_slice($headers, $lastStatusLine); |
| 63 |
} |
| 64 |
} |
| 65 |
|