vendor/guzzlehttp/psr7/src/MessageTrait.php

358 lines · 10912 bytes

  1<?php
  2
  3declare(strict_types=1);
  4
  5namespace GuzzleHttp\Psr7;
  6
  7use Psr\Http\Message\MessageInterface;
  8use Psr\Http\Message\StreamInterface;
  9
 10/**
 11 * Trait implementing functionality common to requests and responses.
 12 */
 13trait MessageTrait
 14{
 15    /** @var string[][] Map of all registered headers, as original name => array of values */
 16    private $headers = [];
 17
 18    /** @var string[] Map of lowercase header name => original name at registration */
 19    private $headerNames = [];
 20
 21    /** @var string */
 22    private $protocol = '1.1';
 23
 24    /** @var StreamInterface|null */
 25    private $stream;
 26
 27    public function getProtocolVersion(): string
 28    {
 29        return $this->protocol;
 30    }
 31
 32    /**
 33     * @return static
 34     */
 35    public function withProtocolVersion($version): MessageInterface
 36    {
 37        if (!\is_string($version)) {
 38            \trigger_deprecation(
 39                'guzzlehttp/psr7',
 40                '2.11',
 41                'Passing %s to MessageInterface::withProtocolVersion() is deprecated; guzzlehttp/psr7 3.0 requires string.',
 42                \get_debug_type($version)
 43            );
 44        }
 45
 46        $this->assertProtocolVersion($version);
 47
 48        if ($this->protocol === $version) {
 49            return $this;
 50        }
 51
 52        $new = clone $this;
 53        $new->protocol = $version;
 54
 55        return $new;
 56    }
 57
 58    public function getHeaders(): array
 59    {
 60        return $this->headers;
 61    }
 62
 63    public function hasHeader($header): bool
 64    {
 65        return isset($this->headerNames[Utils::asciiToLower($header)]);
 66    }
 67
 68    public function getHeader($header): array
 69    {
 70        $header = Utils::asciiToLower($header);
 71
 72        if (!isset($this->headerNames[$header])) {
 73            return [];
 74        }
 75
 76        $header = $this->headerNames[$header];
 77
 78        return $this->headers[$header];
 79    }
 80
 81    public function getHeaderLine($header): string
 82    {
 83        return implode(', ', $this->getHeader($header));
 84    }
 85
 86    /**
 87     * @return static
 88     */
 89    public function withHeader($header, $value): MessageInterface
 90    {
 91        $this->assertHeader($header);
 92        $values = \is_array($value) ? $value : [$value];
 93        foreach ($values as $item) {
 94            if (!\is_string($item) && (\is_scalar($item) || $item === null)) {
 95                \trigger_deprecation(
 96                    'guzzlehttp/psr7',
 97                    '2.11',
 98                    'Passing %s to MessageInterface::withHeader() is deprecated; guzzlehttp/psr7 3.0 requires string|string[].',
 99                    \get_debug_type($item)
100                );
101
102                break;
103            }
104        }
105        $value = $this->normalizeHeaderValue($value);
106        $normalized = Utils::asciiToLower($header);
107
108        $new = clone $this;
109        if (isset($new->headerNames[$normalized])) {
110            unset($new->headers[$new->headerNames[$normalized]]);
111        }
112        $new->headerNames[$normalized] = $header;
113        $new->headers[$header] = $value;
114
115        return $new;
116    }
117
118    /**
119     * @return static
120     */
121    public function withAddedHeader($header, $value): MessageInterface
122    {
123        $this->assertHeader($header);
124        $values = \is_array($value) ? $value : [$value];
125        foreach ($values as $item) {
126            if (!\is_string($item) && (\is_scalar($item) || $item === null)) {
127                \trigger_deprecation(
128                    'guzzlehttp/psr7',
129                    '2.11',
130                    'Passing %s to MessageInterface::withAddedHeader() is deprecated; guzzlehttp/psr7 3.0 requires string|string[].',
131                    \get_debug_type($item)
132                );
133
134                break;
135            }
136        }
137        $value = $this->normalizeHeaderValue($value);
138        $normalized = Utils::asciiToLower($header);
139
140        $new = clone $this;
141        if (isset($new->headerNames[$normalized])) {
142            $header = $this->headerNames[$normalized];
143            $new->headers[$header] = array_merge($this->headers[$header], $value);
144        } else {
145            $new->headerNames[$normalized] = $header;
146            $new->headers[$header] = $value;
147        }
148
149        return $new;
150    }
151
152    /**
153     * @return static
154     */
155    public function withoutHeader($header): MessageInterface
156    {
157        $normalized = Utils::asciiToLower($header);
158
159        if (!isset($this->headerNames[$normalized])) {
160            return $this;
161        }
162
163        $header = $this->headerNames[$normalized];
164
165        $new = clone $this;
166        unset($new->headers[$header], $new->headerNames[$normalized]);
167
168        return $new;
169    }
170
171    public function getBody(): StreamInterface
172    {
173        if (!$this->stream) {
174            $this->stream = Utils::streamFor('');
175        }
176
177        return $this->stream;
178    }
179
180    /**
181     * @return static
182     */
183    public function withBody(StreamInterface $body): MessageInterface
184    {
185        if ($body === $this->stream) {
186            return $this;
187        }
188
189        $new = clone $this;
190        $new->stream = $body;
191
192        return $new;
193    }
194
195    /**
196     * @param (string|string[])[] $headers
197     */
198    private function setHeaders(array $headers): void
199    {
200        $this->headerNames = $this->headers = [];
201        foreach ($headers as $header => $value) {
202            // Numeric array keys are converted to int by PHP.
203            $header = (string) $header;
204
205            $this->assertHeader($header);
206            $values = \is_array($value) ? $value : [$value];
207            foreach ($values as $item) {
208                if (!\is_string($item) && (\is_scalar($item) || $item === null)) {
209                    \trigger_deprecation(
210                        'guzzlehttp/psr7',
211                        '2.11',
212                        'Passing %s to %s::__construct() is deprecated; guzzlehttp/psr7 3.0 requires string|string[].',
213                        \get_debug_type($item),
214                        static::class
215                    );
216
217                    break;
218                }
219            }
220            $value = $this->normalizeHeaderValue($value);
221            $normalized = Utils::asciiToLower($header);
222            if (isset($this->headerNames[$normalized])) {
223                $header = $this->headerNames[$normalized];
224                $this->headers[$header] = array_merge($this->headers[$header], $value);
225            } else {
226                $this->headerNames[$normalized] = $header;
227                $this->headers[$header] = $value;
228            }
229        }
230    }
231
232    /**
233     * @param mixed $value
234     *
235     * @return string[]
236     */
237    private function normalizeHeaderValue($value): array
238    {
239        if (is_array($value) && $value === []) {
240            \trigger_deprecation(
241                'guzzlehttp/psr7',
242                '2.11',
243                'Passing an empty array as a header value is deprecated; guzzlehttp/psr7 3.0 rejects empty header value arrays.'
244            );
245        }
246
247        if (!is_array($value)) {
248            return $this->trimAndValidateHeaderValues([$value]);
249        }
250
251        return $this->trimAndValidateHeaderValues($value);
252    }
253
254    /**
255     * Trims whitespace from the header values.
256     *
257     * Spaces and tabs ought to be excluded by parsers when extracting the field value from a header field.
258     *
259     * header-field = field-name ":" OWS field-value OWS
260     * OWS          = *( SP / HTAB )
261     *
262     * @param mixed[] $values Header values
263     *
264     * @return string[] Trimmed header values
265     *
266     * @see https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.4
267     */
268    private function trimAndValidateHeaderValues(array $values): array
269    {
270        return array_map(function ($value) {
271            if (!is_scalar($value) && null !== $value) {
272                throw new \InvalidArgumentException(sprintf(
273                    'Header value must be scalar or null but %s provided.',
274                    is_object($value) ? get_class($value) : gettype($value)
275                ));
276            }
277
278            // Convert non-finite floats explicitly, as implicit coercion of
279            // NAN emits a warning on PHP 8.5.
280            if (is_float($value) && !is_finite($value)) {
281                $value = is_nan($value) ? 'NAN' : ($value > 0 ? 'INF' : '-INF');
282            }
283
284            $trimmed = trim((string) $value, " \t");
285            $this->assertValue($trimmed);
286
287            return $trimmed;
288        }, array_values($values));
289    }
290
291    /**
292     * @see https://datatracker.ietf.org/doc/html/rfc7230#section-3.2
293     *
294     * @param mixed $header
295     */
296    private function assertHeader($header): void
297    {
298        if (!is_string($header)) {
299            throw new \InvalidArgumentException(sprintf(
300                'Header name must be a string but %s provided.',
301                is_object($header) ? get_class($header) : gettype($header)
302            ));
303        }
304
305        if (!preg_match('/^[a-zA-Z0-9\'`#$%&*+.^_|~!-]+$/D', $header)) {
306            throw new \InvalidArgumentException(
307                sprintf('"%s" is not valid header name.', $header)
308            );
309        }
310    }
311
312    /**
313     * @param mixed $version
314     */
315    private function assertProtocolVersion($version): void
316    {
317        if (is_string($version)) {
318            $this->assertNoLineSeparators($version, 'Protocol version');
319        }
320    }
321
322    private function assertNoLineSeparators(string $value, string $field): void
323    {
324        if (strpbrk($value, "\r\n") !== false) {
325            throw new \InvalidArgumentException($field.' must not contain CR or LF characters.');
326        }
327    }
328
329    /**
330     * @see https://datatracker.ietf.org/doc/html/rfc7230#section-3.2
331     *
332     * field-value    = *( field-content / obs-fold )
333     * field-content  = field-vchar [ 1*( SP / HTAB ) field-vchar ]
334     * field-vchar    = VCHAR / obs-text
335     * VCHAR          = %x21-7E
336     * obs-text       = %x80-FF
337     * obs-fold       = CRLF 1*( SP / HTAB )
338     */
339    private function assertValue(string $value): void
340    {
341        // The regular expression intentionally does not support the obs-fold production, because as
342        // per RFC 7230#3.2.4:
343        //
344        // A sender MUST NOT generate a message that includes
345        // line folding (i.e., that has any field-value that contains a match to
346        // the obs-fold rule) unless the message is intended for packaging
347        // within the message/http media type.
348        //
349        // Clients must not send a request with line folding and a server sending folded headers is
350        // likely very rare. Line folding is a fairly obscure feature of HTTP/1.1 and thus not accepting
351        // folding is not likely to break any legitimate use case.
352        if (!preg_match('/^[\x20\x09\x21-\x7E\x80-\xFF]*$/D', $value)) {
353            throw new \InvalidArgumentException(
354                sprintf('"%s" is not valid header value.', $value)
355            );
356        }
357    }
358}