vendor/guzzlehttp/guzzle/src/Handler/HeaderProcessor.php
97 lines · 2673 bytes
1<?php
2
3namespace GuzzleHttp\Handler;
4
5use GuzzleHttp\Utils;
6
7/**
8 * @internal
9 */
10final class HeaderProcessor
11{
12 /**
13 * Returns the HTTP version, status code, reason phrase, and headers.
14 *
15 * @param string[] $headers
16 *
17 * @return array{0:string, 1:int, 2:?string, 3:array}
18 *
19 * @throws \RuntimeException
20 */
21 public static function parseHeaders(array $headers): array
22 {
23 if ($headers === []) {
24 throw new \RuntimeException('Expected a non-empty array of header data');
25 }
26
27 $headers = self::getLastHeaderBlock(\array_values($headers));
28
29 $statusLine = \array_shift($headers);
30 if ($statusLine === null) {
31 throw new \RuntimeException('Expected a non-empty array of header data');
32 }
33
34 $parts = \explode(' ', $statusLine, 3);
35 $version = \explode('/', $parts[0])[1] ?? null;
36
37 if ($version === null) {
38 throw new \RuntimeException('HTTP version missing from header data');
39 }
40
41 $status = $parts[1] ?? null;
42
43 if ($status === null) {
44 throw new \RuntimeException('HTTP status code missing from header data');
45 }
46
47 if (!\preg_match('/^\d{3}$/D', $status)) {
48 throw new \RuntimeException('HTTP status code is invalid');
49 }
50
51 foreach ($headers as $header) {
52 if (\strpos($header, ':') === false) {
53 throw new \RuntimeException('HTTP header line is invalid');
54 }
55 }
56
57 return [$version, (int) $status, $parts[2] ?? null, Utils::headersFromLines($headers)];
58 }
59
60 public static function isStatusLineCandidate(string $line): bool
61 {
62 return \preg_match('/^HTTP\/[0-9]+(?:\.[0-9]+)? [0-9]{3}(?: [^\r\n]*)?(?:\r\n|\r|\n)?$/iD', $line) === 1;
63 }
64
65 public static function isValidHeaderFieldLine(string $line): bool
66 {
67 $parts = \explode(':', $line, 2);
68
69 if (!isset($parts[1])) {
70 return false;
71 }
72
73 if (!\preg_match('/^[a-zA-Z0-9\'`#$%&*+.^_|~!-]+$/D', $parts[0])) {
74 return false;
75 }
76
77 return \preg_match('/^[\x20\x09\x21-\x7E\x80-\xFF]*(?:\r\n|\r|\n)?$/D', \trim($parts[1], " \t")) === 1;
78 }
79
80 /**
81 * @param non-empty-list<string> $headers
82 *
83 * @return list<string>
84 */
85 private static function getLastHeaderBlock(array $headers): array
86 {
87 $lastStatusLine = 0;
88
89 foreach ($headers as $index => $line) {
90 if (self::isStatusLineCandidate($line)) {
91 $lastStatusLine = $index;
92 }
93 }
94
95 return \array_slice($headers, $lastStatusLine);
96 }
97}