PluginProbe
Yoast SEO – Advanced SEO with real-time guidance and built-in AI / 28.0
Yoast SEO – Advanced SEO with real-time guidance and built-in AI v28.0
28.5 28.4 28.3 28.2 28.1 28.0 27.9 27.8 27.7 27.6 27.5 trunk 18.0 18.1 18.2 18.3 18.4 18.4.1 18.5 18.5.1 18.6 18.7 18.8 18.9 19.0 All 129 releases
wordpress-seo / vendor_prefixed / guzzlehttp / psr7 / src / Message.php

Message.php in Yoast SEO – Advanced SEO with real-time guidance and built-in AI 28.0, at vendor_prefixed/guzzlehttp/psr7/src/Message.php

253 lines 10.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 declare (strict_types=1);
4 namespace YoastSEO_Vendor\GuzzleHttp\Psr7;
5
6 use YoastSEO_Vendor\Psr\Http\Message\MessageInterface;
7 use YoastSEO_Vendor\Psr\Http\Message\RequestInterface;
8 use YoastSEO_Vendor\Psr\Http\Message\ResponseInterface;
9 final class Message
10 {
11 /**
12 * Returns the string representation of an HTTP message.
13 *
14 * @param MessageInterface $message Message to convert to a string.
15 */
16 public static function toString(\YoastSEO_Vendor\Psr\Http\Message\MessageInterface $message) : string
17 {
18 if ($message instanceof \YoastSEO_Vendor\Psr\Http\Message\RequestInterface) {
19 $msg = \trim($message->getMethod() . ' ' . $message->getRequestTarget()) . ' HTTP/' . $message->getProtocolVersion();
20 if (!$message->hasHeader('host')) {
21 $msg .= "\r\nHost: " . $message->getUri()->getHost();
22 }
23 } elseif ($message instanceof \YoastSEO_Vendor\Psr\Http\Message\ResponseInterface) {
24 $msg = 'HTTP/' . $message->getProtocolVersion() . ' ' . $message->getStatusCode() . ' ' . $message->getReasonPhrase();
25 } else {
26 throw new \InvalidArgumentException('Unknown message type');
27 }
28 foreach ($message->getHeaders() as $name => $values) {
29 if (\is_string($name) && \strtolower($name) === 'set-cookie') {
30 foreach ($values as $value) {
31 $msg .= "\r\n{$name}: " . $value;
32 }
33 } else {
34 $msg .= "\r\n{$name}: " . \implode(', ', $values);
35 }
36 }
37 return "{$msg}\r\n\r\n" . $message->getBody();
38 }
39 /**
40 * Get a short summary of the message body.
41 *
42 * Will return `null` if the response is not printable.
43 *
44 * @param MessageInterface $message The message to get the body summary
45 * @param int $truncateAt The maximum allowed size of the summary
46 */
47 public static function bodySummary(\YoastSEO_Vendor\Psr\Http\Message\MessageInterface $message, int $truncateAt = 120) : ?string
48 {
49 $body = $message->getBody();
50 if (!$body->isSeekable() || !$body->isReadable()) {
51 return null;
52 }
53 $size = $body->getSize();
54 if ($size === 0) {
55 return null;
56 }
57 $body->rewind();
58 $summary = $body->read($truncateAt);
59 if ($size > $truncateAt) {
60 if (\preg_match('//u', $summary) !== 1) {
61 $summary = self::trimTrailingIncompleteUtf8Character($summary, $body->read(3));
62 }
63 $summary .= ' (truncated...)';
64 }
65 $body->rewind();
66 // Matches any printable character, including unicode characters:
67 // letters, marks, numbers, punctuation, spacing, and separators.
68 if (\preg_match('/[^\\pL\\pM\\pN\\pP\\pS\\pZ\\n\\r\\t]/u', $summary) !== 0) {
69 return null;
70 }
71 return $summary;
72 }
73 /**
74 * Trims a partial UTF-8 character from the end of a truncated string.
75 */
76 private static function trimTrailingIncompleteUtf8Character(string $summary, string $lookahead) : string
77 {
78 $length = \strlen($summary);
79 if ($length === 0) {
80 return $summary;
81 }
82 $start = $length - 1;
83 while ($start >= 0) {
84 $byte = \ord($summary[$start]);
85 if ($byte < 0x80 || $byte > 0xbf) {
86 break;
87 }
88 --$start;
89 }
90 if ($start < 0) {
91 return $summary;
92 }
93 $lead = \ord($summary[$start]);
94 if ($lead >= 0xc2 && $lead <= 0xdf) {
95 $expectedLength = 2;
96 } elseif ($lead >= 0xe0 && $lead <= 0xef) {
97 $expectedLength = 3;
98 } elseif ($lead >= 0xf0 && $lead <= 0xf4) {
99 $expectedLength = 4;
100 } else {
101 return $summary;
102 }
103 $availableLength = $length - $start;
104 if ($availableLength >= $expectedLength) {
105 return $summary;
106 }
107 $sequence = \substr($summary, $start) . \substr($lookahead, 0, $expectedLength - $availableLength);
108 if (\strlen($sequence) !== $expectedLength || \preg_match('//u', $sequence) !== 1) {
109 return $summary;
110 }
111 return \substr($summary, 0, $start);
112 }
113 /**
114 * Attempts to rewind a message body and throws an exception on failure.
115 *
116 * The body of the message will only be rewound if a call to `tell()`
117 * returns a value other than `0`.
118 *
119 * @param MessageInterface $message Message to rewind
120 *
121 * @throws \RuntimeException
122 */
123 public static function rewindBody(\YoastSEO_Vendor\Psr\Http\Message\MessageInterface $message) : void
124 {
125 $body = $message->getBody();
126 if ($body->tell()) {
127 $body->rewind();
128 }
129 }
130 /**
131 * Parses an HTTP message into an associative array.
132 *
133 * The array contains the "start-line" key containing the start line of
134 * the message, "headers" key containing an associative array of header
135 * array values, and a "body" key containing the body of the message.
136 *
137 * @param string $message HTTP request or response to parse.
138 */
139 public static function parseMessage(string $message) : array
140 {
141 if (!$message) {
142 throw new \InvalidArgumentException('Invalid message');
143 }
144 $message = \ltrim($message, "\r\n");
145 $messageParts = \preg_split("/\r?\n\r?\n/", $message, 2);
146 if ($messageParts === \false || \count($messageParts) !== 2) {
147 throw new \InvalidArgumentException('Invalid message: Missing header delimiter');
148 }
149 [$rawHeaders, $body] = $messageParts;
150 $rawHeaders .= "\r\n";
151 // Put back the delimiter we split previously
152 $headerParts = \preg_split("/\r?\n/", $rawHeaders, 2);
153 if ($headerParts === \false || \count($headerParts) !== 2) {
154 throw new \InvalidArgumentException('Invalid message: Missing status line');
155 }
156 [$startLine, $rawHeaders] = $headerParts;
157 if (\preg_match("/(?:^HTTP\\/|^[A-Z]+ \\S+ HTTP\\/)(\\d+(?:\\.\\d+)?)/i", $startLine, $matches) && $matches[1] === '1.0') {
158 // Header folding is deprecated for HTTP/1.1, but allowed in HTTP/1.0
159 $rawHeaders = \preg_replace(\YoastSEO_Vendor\GuzzleHttp\Psr7\Rfc7230::HEADER_FOLD_REGEX, ' ', $rawHeaders);
160 }
161 /** @var array[] $headerLines */
162 $count = \preg_match_all(\YoastSEO_Vendor\GuzzleHttp\Psr7\Rfc7230::HEADER_REGEX, $rawHeaders, $headerLines, \PREG_SET_ORDER);
163 // If these aren't the same, then one line didn't match and there's an invalid header.
164 if ($count !== \substr_count($rawHeaders, "\n")) {
165 // Folding is deprecated, see https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.4
166 if (\preg_match(\YoastSEO_Vendor\GuzzleHttp\Psr7\Rfc7230::HEADER_FOLD_REGEX, $rawHeaders)) {
167 throw new \InvalidArgumentException('Invalid header syntax: Obsolete line folding');
168 }
169 throw new \InvalidArgumentException('Invalid header syntax');
170 }
171 $headers = [];
172 foreach ($headerLines as $headerLine) {
173 $headers[$headerLine[1]][] = $headerLine[2];
174 }
175 return ['start-line' => $startLine, 'headers' => $headers, 'body' => $body];
176 }
177 /**
178 * Constructs a URI for an HTTP request message.
179 *
180 * @param string $path Path from the start-line
181 * @param array $headers Array of headers (each value an array).
182 */
183 public static function parseRequestUri(string $path, array $headers) : string
184 {
185 $host = self::getHostFromHeaders($headers);
186 // If no host is found, then a full URI cannot be constructed.
187 if ($host === null) {
188 return $path;
189 }
190 $scheme = \substr($host, -4) === ':443' ? 'https' : 'http';
191 return $scheme . '://' . $host . '/' . \ltrim($path, '/');
192 }
193 /**
194 * @param array $headers Array of headers (each value an array).
195 */
196 private static function getHostFromHeaders(array $headers) : ?string
197 {
198 $hostKey = \array_filter(\array_keys($headers), function ($k) {
199 // Numeric array keys are converted to int by PHP.
200 $k = (string) $k;
201 return \strtolower($k) === 'host';
202 });
203 if (!$hostKey) {
204 return null;
205 }
206 $host = $headers[\reset($hostKey)][0];
207 if (!\is_string($host) || \YoastSEO_Vendor\GuzzleHttp\Psr7\Rfc7230::parseHostHeader($host) === null) {
208 throw new \InvalidArgumentException('Invalid request string');
209 }
210 return $host;
211 }
212 /**
213 * Parses a request message string into a request object.
214 *
215 * @param string $message Request message string.
216 */
217 public static function parseRequest(string $message) : \YoastSEO_Vendor\Psr\Http\Message\RequestInterface
218 {
219 $data = self::parseMessage($message);
220 if (\strpbrk($data['start-line'], "\r\n") !== \false) {
221 throw new \InvalidArgumentException('Invalid request string');
222 }
223 $matches = [];
224 if (!\preg_match('/^[\\S]+\\s+([a-zA-Z]+:\\/\\/|\\/).*/', $data['start-line'], $matches)) {
225 throw new \InvalidArgumentException('Invalid request string');
226 }
227 $parts = \explode(' ', $data['start-line'], 3);
228 $version = isset($parts[2]) ? \explode('/', $parts[2])[1] : '1.1';
229 $request = new \YoastSEO_Vendor\GuzzleHttp\Psr7\Request($parts[0], $matches[1] === '/' ? self::parseRequestUri($parts[1], $data['headers']) : $parts[1], $data['headers'], $data['body'], $version);
230 return $matches[1] === '/' ? $request : $request->withRequestTarget($parts[1]);
231 }
232 /**
233 * Parses a response message string into a response object.
234 *
235 * @param string $message Response message string.
236 */
237 public static function parseResponse(string $message) : \YoastSEO_Vendor\Psr\Http\Message\ResponseInterface
238 {
239 $data = self::parseMessage($message);
240 if (\strpbrk($data['start-line'], "\r\n") !== \false) {
241 throw new \InvalidArgumentException('Invalid response string');
242 }
243 // According to https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2
244 // the space between status-code and reason-phrase is required. But
245 // browsers accept responses without space and reason as well.
246 if (!\preg_match('/^HTTP\\/.* [0-9]{3}( .*|$)/', $data['start-line'])) {
247 throw new \InvalidArgumentException('Invalid response string: ' . $data['start-line']);
248 }
249 $parts = \explode(' ', $data['start-line'], 3);
250 return new \YoastSEO_Vendor\GuzzleHttp\Psr7\Response((int) $parts[1], $data['headers'], $data['body'], \explode('/', $parts[0])[1], $parts[2] ?? null);
251 }
252 }
253