vendor/guzzlehttp/psr7/src/Utils.php
724 lines · 25287 bytes
1<?php
2
3declare(strict_types=1);
4
5namespace GuzzleHttp\Psr7;
6
7use Psr\Http\Message\RequestInterface;
8use Psr\Http\Message\StreamInterface;
9use Psr\Http\Message\UriInterface;
10
11final class Utils
12{
13 /**
14 * Converts ASCII uppercase letters in a string to lowercase.
15 *
16 * Unlike strtolower(), which honors LC_CTYPE before PHP 8.2, the
17 * conversion is locale-independent and leaves every non-ASCII byte
18 * unchanged, as HTTP protocol elements require.
19 */
20 public static function asciiToLower(string $string): string
21 {
22 return strtr($string, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
23 }
24
25 /**
26 * Converts ASCII lowercase letters in a string to uppercase.
27 *
28 * Unlike strtoupper(), which honors LC_CTYPE before PHP 8.2, the
29 * conversion is locale-independent and leaves every non-ASCII byte
30 * unchanged, as HTTP protocol elements require.
31 */
32 public static function asciiToUpper(string $string): string
33 {
34 return strtr($string, 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
35 }
36
37 /**
38 * Converts the first character of a string to uppercase when it is an
39 * ASCII lowercase letter.
40 *
41 * Unlike ucfirst(), which honors LC_CTYPE before PHP 8.2, the conversion
42 * is locale-independent and leaves every non-ASCII byte unchanged, as
43 * HTTP protocol elements require.
44 */
45 public static function asciiUcFirst(string $string): string
46 {
47 if ($string === '') {
48 return '';
49 }
50
51 return self::asciiToUpper($string[0]).substr($string, 1);
52 }
53
54 /**
55 * Checks whether the haystack contains the needle, comparing ASCII
56 * letters case-insensitively and without locale sensitivity.
57 */
58 public static function caselessContains(string $haystack, string $needle): bool
59 {
60 return str_contains(self::asciiToLower($haystack), self::asciiToLower($needle));
61 }
62
63 /**
64 * Checks whether two strings are equal, comparing ASCII letters
65 * case-insensitively and without locale sensitivity.
66 */
67 public static function caselessEquals(string $left, string $right): bool
68 {
69 return self::asciiToLower($left) === self::asciiToLower($right);
70 }
71
72 /**
73 * Remove the items given by the keys, case insensitively from the data.
74 *
75 * @param (string|int)[] $keys
76 */
77 public static function caselessRemove(array $keys, array $data): array
78 {
79 $result = [];
80
81 foreach ($keys as &$key) {
82 $key = self::asciiToLower((string) $key);
83 }
84
85 foreach ($data as $k => $v) {
86 if (!in_array(self::asciiToLower((string) $k), $keys)) {
87 $result[$k] = $v;
88 }
89 }
90
91 return $result;
92 }
93
94 /**
95 * Copy the contents of a stream into another stream until the given number
96 * of bytes have been read.
97 *
98 * The copy stops if the destination write returns 0, for example a
99 * BufferStream at its high water mark or a full DroppingStream. For a
100 * guaranteed full copy use a normal writable stream such as a file or
101 * php://temp stream.
102 *
103 * @param StreamInterface $source Stream to read from
104 * @param StreamInterface $dest Stream to write to
105 * @param int $maxLen Maximum number of bytes to read. Pass -1
106 * to read the entire stream.
107 *
108 * @throws \RuntimeException on error.
109 */
110 public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1): void
111 {
112 $bufferSize = 8192;
113
114 if ($maxLen === -1) {
115 while (!$source->eof()) {
116 $buf = $source->read($bufferSize);
117 if ($buf === '') {
118 break;
119 }
120
121 if (!self::writeAll($dest, $buf)) {
122 break;
123 }
124 }
125 } else {
126 $remaining = $maxLen;
127 while ($remaining > 0 && !$source->eof()) {
128 $buf = $source->read(min($bufferSize, $remaining));
129 $len = strlen($buf);
130 if (!$len) {
131 break;
132 }
133 $remaining -= $len;
134 if (!self::writeAll($dest, $buf)) {
135 break;
136 }
137 }
138 }
139 }
140
141 /**
142 * Writes the full buffer to the destination, retrying short writes.
143 *
144 * Returns false when the destination write returns 0 or less.
145 */
146 private static function writeAll(StreamInterface $dest, string $buf): bool
147 {
148 $written = 0;
149 $len = strlen($buf);
150
151 while ($written < $len) {
152 $result = $dest->write(substr($buf, $written));
153 if ($result <= 0) {
154 return false;
155 }
156
157 $written += $result;
158 }
159
160 return true;
161 }
162
163 /**
164 * Copy the contents of a stream into a string until the given number of
165 * bytes have been read.
166 *
167 * @param StreamInterface $stream Stream to read
168 * @param int $maxLen Maximum number of bytes to read. Pass -1
169 * to read the entire stream.
170 *
171 * @throws \RuntimeException on error.
172 */
173 public static function copyToString(StreamInterface $stream, int $maxLen = -1): string
174 {
175 $buffer = '';
176
177 if ($maxLen === -1) {
178 while (!$stream->eof()) {
179 $buf = $stream->read(1048576);
180 if ($buf === '') {
181 break;
182 }
183 $buffer .= $buf;
184 }
185
186 return $buffer;
187 }
188
189 $len = 0;
190 while (!$stream->eof() && $len < $maxLen) {
191 $buf = $stream->read($maxLen - $len);
192 if ($buf === '') {
193 break;
194 }
195 $buffer .= $buf;
196 $len = strlen($buffer);
197 }
198
199 return $buffer;
200 }
201
202 /**
203 * Calculate a hash of a stream.
204 *
205 * This method reads the entire stream to calculate a rolling hash, based
206 * on PHP's `hash_init` functions.
207 *
208 * @param StreamInterface $stream Stream to calculate the hash for
209 * @param string $algo Hash algorithm (e.g. md5, crc32, etc)
210 * @param bool $rawOutput Whether or not to use raw output
211 *
212 * @throws \RuntimeException on error.
213 */
214 public static function hash(StreamInterface $stream, string $algo, bool $rawOutput = false): string
215 {
216 $pos = $stream->tell();
217
218 if ($pos > 0) {
219 $stream->rewind();
220 }
221
222 $ctx = hash_init($algo);
223 while (!$stream->eof()) {
224 hash_update($ctx, $stream->read(1048576));
225 }
226
227 $out = hash_final($ctx, $rawOutput);
228 $stream->seek($pos);
229
230 return $out;
231 }
232
233 /**
234 * Clone and modify a request with the given changes.
235 *
236 * This method is useful for reducing the number of clones needed to mutate
237 * a message.
238 *
239 * The changes can be one of:
240 * - method: (string) Changes the HTTP method.
241 * - set_headers: (array) Sets the given headers. Values must be strings
242 * or non-empty arrays of strings.
243 * - remove_headers: (array) Remove the given headers. Values may be
244 * strings or integers.
245 * - body: (mixed) Sets the given body. Present non-null values are converted
246 * with self::streamFor(), including scalar values, resources, streams,
247 * iterators, callable arrays, closures, invokable objects, and objects
248 * with __toString(). String inputs remain literal bodies.
249 * - uri: (UriInterface) Set the URI.
250 * - query: (string) Set the query string value of the URI.
251 * - version: (string) Set the protocol version.
252 *
253 * @param RequestInterface $request Request to clone and modify.
254 * @param array $changes Changes to apply.
255 */
256 public static function modifyRequest(RequestInterface $request, array $changes): RequestInterface
257 {
258 if (!$changes) {
259 return $request;
260 }
261
262 self::warnOnInvalidModifyRequestChanges($changes);
263
264 $headers = $request->getHeaders();
265
266 if (!isset($changes['uri'])) {
267 $uri = $request->getUri();
268 } else {
269 // Remove the host header if one is on the URI
270 $host = $changes['uri']->getHost();
271 if ($host !== '') {
272 if (isset($changes['set_headers']) && is_array($changes['set_headers'])) {
273 foreach (array_keys($changes['set_headers']) as $header) {
274 if (self::asciiToLower((string) $header) === 'host') {
275 throw new \InvalidArgumentException(
276 'Cannot modify request with both a URI containing a host and an explicit Host header.'
277 );
278 }
279 }
280 }
281
282 $changes['set_headers']['Host'] = $host;
283
284 if ($port = $changes['uri']->getPort()) {
285 $standardPorts = ['http' => 80, 'https' => 443];
286 $scheme = $changes['uri']->getScheme();
287 if (isset($standardPorts[$scheme]) && $port != $standardPorts[$scheme]) {
288 $changes['set_headers']['Host'] .= ':'.$port;
289 }
290 }
291 }
292 $uri = $changes['uri'];
293 }
294
295 if (!empty($changes['remove_headers'])) {
296 $headers = self::caselessRemove($changes['remove_headers'], $headers);
297 }
298
299 if (!empty($changes['set_headers'])) {
300 $headers = self::caselessRemove(array_keys($changes['set_headers']), $headers);
301 $headers = $changes['set_headers'] + $headers;
302 }
303
304 if (isset($changes['query'])) {
305 $uri = $uri->withQuery($changes['query']);
306 }
307
308 $hasHost = false;
309 foreach (array_keys($headers) as $header) {
310 if (self::asciiToLower((string) $header) === 'host') {
311 $hasHost = true;
312 break;
313 }
314 }
315
316 // Match Request::__construct() by adding a Host header when one is not provided.
317 if (!$hasHost && $uri->getHost() !== '') {
318 $host = $uri->getHost();
319
320 if (($port = $uri->getPort()) !== null) {
321 $host .= ':'.$port;
322 }
323
324 $headers = ['Host' => [$host]] + $headers;
325 }
326
327 $new = $request;
328
329 if (isset($changes['method'])) {
330 $new = $new->withMethod($changes['method']);
331 }
332
333 if (isset($changes['uri']) || isset($changes['query'])) {
334 $new = $new->withUri($uri, true);
335 }
336
337 if ($headers !== $new->getHeaders()) {
338 foreach (array_keys($new->getHeaders()) as $header) {
339 /** @var RequestInterface */
340 $new = $new->withoutHeader((string) $header);
341 }
342
343 $addedHeaders = [];
344 foreach ($headers as $header => $value) {
345 $header = (string) $header;
346 $normalized = self::asciiToLower($header);
347
348 if (isset($addedHeaders[$normalized])) {
349 /** @var RequestInterface */
350 $new = $new->withAddedHeader($addedHeaders[$normalized], $value);
351 } else {
352 /** @var RequestInterface */
353 $new = $new->withHeader($header, $value);
354 $addedHeaders[$normalized] = $header;
355 }
356 }
357 }
358
359 if (isset($changes['body'])) {
360 /** @var RequestInterface */
361 $new = $new->withBody(self::streamFor($changes['body']));
362 }
363
364 if (isset($changes['version'])) {
365 /** @var RequestInterface */
366 $new = $new->withProtocolVersion($changes['version']);
367 }
368
369 return $new;
370 }
371
372 /**
373 * @param array<array-key, mixed> $changes
374 */
375 private static function warnOnInvalidModifyRequestChanges(array $changes): void
376 {
377 foreach (['method', 'query', 'version'] as $key) {
378 if (\array_key_exists($key, $changes) && !\is_string($changes[$key])) {
379 self::warnOnInvalidModifyRequestChange($key, 'string', $changes[$key]);
380 }
381 }
382
383 if (\array_key_exists('uri', $changes) && !$changes['uri'] instanceof UriInterface) {
384 self::warnOnInvalidModifyRequestChange('uri', 'UriInterface', $changes['uri']);
385 }
386
387 if (\array_key_exists('body', $changes) && $changes['body'] === null) {
388 self::warnOnInvalidModifyRequestChange('body', 'resource|string|int|float|bool|StreamInterface|callable|\Iterator|\Stringable', $changes['body']);
389 }
390
391 if (\array_key_exists('set_headers', $changes)) {
392 if (!\is_array($changes['set_headers'])) {
393 self::warnOnInvalidModifyRequestChange('set_headers', 'array<array-key, string|non-empty-array<array-key, string>>', $changes['set_headers']);
394 } else {
395 foreach ($changes['set_headers'] as $header => $value) {
396 $headerPath = \sprintf('set_headers.%s', (string) $header);
397
398 if (\is_array($value)) {
399 if ($value === []) {
400 self::warnOnInvalidModifyRequestChange($headerPath, 'string|non-empty-array<array-key, string>', $value);
401
402 break;
403 }
404
405 foreach ($value as $index => $item) {
406 if (!\is_string($item)) {
407 self::warnOnInvalidModifyRequestChange(\sprintf('%s.%s', $headerPath, (string) $index), 'string', $item);
408
409 break 2;
410 }
411 }
412 } elseif (!\is_string($value)) {
413 self::warnOnInvalidModifyRequestChange($headerPath, 'string|non-empty-array<array-key, string>', $value);
414
415 break;
416 }
417 }
418 }
419 }
420
421 if (!\array_key_exists('remove_headers', $changes)) {
422 return;
423 }
424
425 if (!\is_array($changes['remove_headers'])) {
426 self::warnOnInvalidModifyRequestChange('remove_headers', 'array<array-key, string|int>', $changes['remove_headers']);
427
428 return;
429 }
430
431 foreach ($changes['remove_headers'] as $index => $header) {
432 if (!\is_string($header) && !\is_int($header)) {
433 self::warnOnInvalidModifyRequestChange(\sprintf('remove_headers.%s', (string) $index), 'string|int', $header);
434
435 return;
436 }
437 }
438 }
439
440 /**
441 * @param mixed $value
442 */
443 private static function warnOnInvalidModifyRequestChange(string $key, string $expected, $value): void
444 {
445 \trigger_deprecation(
446 'guzzlehttp/psr7',
447 '2.11',
448 'Passing %s to Utils::modifyRequest() change "%s" is deprecated; guzzlehttp/psr7 3.0 requires %s.',
449 \get_debug_type($value),
450 $key,
451 $expected
452 );
453 }
454
455 /**
456 * Read a line from the stream up to the maximum allowed buffer length.
457 *
458 * @param StreamInterface $stream Stream to read from
459 * @param int|null $maxLength Maximum buffer length
460 */
461 public static function readLine(StreamInterface $stream, ?int $maxLength = null): string
462 {
463 $buffer = '';
464 $size = 0;
465
466 while (!$stream->eof()) {
467 if ('' === ($byte = $stream->read(1))) {
468 return $buffer;
469 }
470 $buffer .= $byte;
471 // Break when a new line is found or the max length - 1 is reached
472 if ($byte === "\n" || ++$size === $maxLength - 1) {
473 break;
474 }
475 }
476
477 return $buffer;
478 }
479
480 /**
481 * Redact the password in the user info part of a URI.
482 */
483 public static function redactUserInfo(UriInterface $uri): UriInterface
484 {
485 $userInfo = $uri->getUserInfo();
486
487 if (false !== ($pos = \strpos($userInfo, ':'))) {
488 return $uri->withUserInfo(\substr($userInfo, 0, $pos), '***');
489 }
490
491 return $uri;
492 }
493
494 /**
495 * Create a new stream based on the input type.
496 *
497 * Options is an associative array that can contain the following keys:
498 * - metadata: Array of custom metadata.
499 * - size: Size of the stream.
500 *
501 * This method accepts the following `$resource` types:
502 * - `Psr\Http\Message\StreamInterface`: Returns the value as-is.
503 * - `string`: Creates a stream object that uses the given string as the contents.
504 * - `resource`: Creates a stream object that wraps the given PHP stream resource.
505 * - `Iterator`: If the provided value implements `Iterator`, then a read-only
506 * stream object will be created that wraps the given iterable. Each time the
507 * stream is read from, data from the iterator will fill a buffer and will be
508 * continuously called until the buffer is equal to the requested read size.
509 * Subsequent read calls will first read from the buffer and then call `next`
510 * on the underlying iterator until it is exhausted.
511 * - `object` with `__toString()`: If the object has the `__toString()` method,
512 * the object will be cast to a string and then a stream will be returned that
513 * uses the string value.
514 * - `NULL`: When `null` is passed, an empty stream object is returned.
515 * - `callable`: When a callable array, closure, or invokable object is passed
516 * and no earlier resource or object rule applies, a read-only stream object
517 * will be created that invokes the given callable. The callable is invoked
518 * with the suggested number of bytes to read. The callable can return fewer
519 * or more bytes than requested, but MUST return `false` or `null` when there
520 * is no more data to return. Any additional bytes will be buffered and used
521 * in subsequent reads. String inputs are always treated as string bodies,
522 * even when they name callable functions.
523 *
524 * Passing a non-string scalar (`int`, `float`, or `bool`) is deprecated; cast
525 * it to a string instead. guzzlehttp/psr7 3.0 will reject non-string scalars.
526 *
527 * @param resource|string|int|float|bool|StreamInterface|callable|\Iterator|null $resource Entity body data
528 * @param array{size?: int, metadata?: array} $options Additional options
529 *
530 * @throws \InvalidArgumentException if the $resource arg is not valid.
531 */
532 public static function streamFor($resource = '', array $options = []): StreamInterface
533 {
534 if (is_scalar($resource)) {
535 if (!is_string($resource)) {
536 \trigger_deprecation(
537 'guzzlehttp/psr7',
538 '2.12',
539 'Passing %s to Utils::streamFor() is deprecated; cast it to a string. guzzlehttp/psr7 3.0 will only accept string, resource, StreamInterface, Stringable, Iterator, callable, or null.',
540 \gettype($resource)
541 );
542
543 if (is_float($resource) && !is_finite($resource)) {
544 // Normalized only to avoid PHP 8.5's (string) NAN warning
545 // while deprecated; 3.0 rejects non-finite floats with every
546 // other non-string scalar.
547 $resource = is_nan($resource) ? 'NAN' : ($resource > 0 ? 'INF' : '-INF');
548 }
549 }
550
551 $stream = self::tryFopen('php://temp', 'r+');
552 if ($resource !== '') {
553 fwrite($stream, (string) $resource);
554 fseek($stream, 0);
555 }
556
557 return new Stream($stream, $options);
558 }
559
560 switch (gettype($resource)) {
561 case 'resource':
562 /*
563 * The 'php://input' is a special stream with quirks and inconsistencies.
564 * We avoid using that stream by reading it into php://temp
565 */
566
567 /** @var resource $resource */
568 if ((\stream_get_meta_data($resource)['uri'] ?? '') === 'php://input') {
569 $stream = self::tryFopen('php://temp', 'w+');
570 stream_copy_to_stream($resource, $stream);
571 fseek($stream, 0);
572 $resource = $stream;
573 }
574
575 return new Stream($resource, $options);
576 case 'object':
577 /** @var object $resource */
578 if ($resource instanceof StreamInterface) {
579 return $resource;
580 } elseif ($resource instanceof \Iterator) {
581 return new PumpStream(function () use ($resource) {
582 if (!$resource->valid()) {
583 return false;
584 }
585 $result = $resource->current();
586 $resource->next();
587
588 return $result;
589 }, $options);
590 } elseif (method_exists($resource, '__toString')) {
591 return self::streamFor((string) $resource, $options);
592 }
593 break;
594 case 'NULL':
595 return new Stream(self::tryFopen('php://temp', 'r+'), $options);
596 }
597
598 if (is_callable($resource)) {
599 return new PumpStream($resource, $options);
600 }
601
602 throw new \InvalidArgumentException('Invalid resource type: '.gettype($resource));
603 }
604
605 /**
606 * Safely opens a PHP stream resource using a filename.
607 *
608 * When fopen fails, PHP normally raises a warning. This function adds an
609 * error handler that checks for errors and throws an exception instead.
610 *
611 * @param string $filename File to open
612 * @param string $mode Mode used to open the file
613 *
614 * @return resource
615 *
616 * @throws \RuntimeException if the file cannot be opened
617 */
618 public static function tryFopen(string $filename, string $mode)
619 {
620 $ex = null;
621 set_error_handler(static function (int $errno, string $errstr) use ($filename, $mode, &$ex): bool {
622 $ex = new \RuntimeException(sprintf(
623 'Unable to open "%s" using mode "%s": %s',
624 $filename,
625 $mode,
626 $errstr
627 ));
628
629 return true;
630 });
631
632 try {
633 /** @var resource $handle */
634 $handle = fopen($filename, $mode);
635 } catch (\Throwable $e) {
636 $ex = new \RuntimeException(sprintf(
637 'Unable to open "%s" using mode "%s": %s',
638 $filename,
639 $mode,
640 $e->getMessage()
641 ), 0, $e);
642 }
643
644 restore_error_handler();
645
646 if ($ex) {
647 /** @var \RuntimeException $ex */
648 throw $ex;
649 }
650
651 return $handle;
652 }
653
654 /**
655 * Safely gets the contents of a given stream.
656 *
657 * When stream_get_contents fails, PHP normally raises a warning. This
658 * function adds an error handler that checks for errors and throws an
659 * exception instead.
660 *
661 * @param resource $stream
662 *
663 * @throws \RuntimeException if the stream cannot be read
664 */
665 public static function tryGetContents($stream): string
666 {
667 $ex = null;
668 set_error_handler(static function (int $errno, string $errstr) use (&$ex): bool {
669 $ex = new \RuntimeException(sprintf(
670 'Unable to read stream contents: %s',
671 $errstr
672 ));
673
674 return true;
675 });
676
677 try {
678 /** @var string|false $contents */
679 $contents = stream_get_contents($stream);
680
681 if ($contents === false) {
682 $ex = new \RuntimeException('Unable to read stream contents');
683 }
684 } catch (\Throwable $e) {
685 $ex = new \RuntimeException(sprintf(
686 'Unable to read stream contents: %s',
687 $e->getMessage()
688 ), 0, $e);
689 }
690
691 restore_error_handler();
692
693 if ($ex) {
694 /** @var \RuntimeException $ex */
695 throw $ex;
696 }
697
698 return $contents;
699 }
700
701 /**
702 * Returns a UriInterface for the given value.
703 *
704 * This function accepts a string or UriInterface and returns a
705 * UriInterface for the given value. If the value is already a
706 * UriInterface, it is returned as-is.
707 *
708 * @param string|UriInterface $uri
709 *
710 * @throws \InvalidArgumentException
711 */
712 public static function uriFor($uri): UriInterface
713 {
714 if ($uri instanceof UriInterface) {
715 return $uri;
716 }
717
718 if (is_string($uri)) {
719 return new Uri($uri);
720 }
721
722 throw new \InvalidArgumentException('URI must be a string or UriInterface');
723 }
724}