| 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}$/D', $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 |
public static function isStatusLineCandidate(string $line) : bool |
| 50 |
{ |
| 51 |
return \preg_match('/^HTTP\\/[0-9]+(?:\\.[0-9]+)? [0-9]{3}(?: [^\\r\\n]*)?(?:\\r\\n|\\r|\\n)?$/iD', $line) === 1; |
| 52 |
} |
| 53 |
public static function isValidHeaderFieldLine(string $line) : bool |
| 54 |
{ |
| 55 |
$parts = \explode(':', $line, 2); |
| 56 |
if (!isset($parts[1])) { |
| 57 |
return \false; |
| 58 |
} |
| 59 |
if (!\preg_match('/^[a-zA-Z0-9\'`#$%&*+.^_|~!-]+$/D', $parts[0])) { |
| 60 |
return \false; |
| 61 |
} |
| 62 |
return \preg_match('/^[\\x20\\x09\\x21-\\x7E\\x80-\\xFF]*(?:\\r\\n|\\r|\\n)?$/D', \trim($parts[1], " \t")) === 1; |
| 63 |
} |
| 64 |
/** |
| 65 |
* @param non-empty-list<string> $headers |
| 66 |
* |
| 67 |
* @return list<string> |
| 68 |
*/ |
| 69 |
private static function getLastHeaderBlock(array $headers) : array |
| 70 |
{ |
| 71 |
$lastStatusLine = 0; |
| 72 |
foreach ($headers as $index => $line) { |
| 73 |
if (self::isStatusLineCandidate($line)) { |
| 74 |
$lastStatusLine = $index; |
| 75 |
} |
| 76 |
} |
| 77 |
return \array_slice($headers, $lastStatusLine); |
| 78 |
} |
| 79 |
} |
| 80 |
|