Debian Codegraph @

vendor/guzzlehttp/psr7/src/Utils.php

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