PluginProbe
Yoast SEO – Advanced SEO with real-time guidance and built-in AI / 28.5
Yoast SEO – Advanced SEO with real-time guidance and built-in AI v28.5
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 / MultipartStream.php

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

226 lines 10.9 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\StreamInterface;
7 /**
8 * Stream that when read returns bytes for a streaming multipart or
9 * multipart/form-data stream.
10 */
11 final class MultipartStream implements \YoastSEO_Vendor\Psr\Http\Message\StreamInterface
12 {
13 use StreamDecoratorTrait;
14 /** @var string */
15 private $boundary;
16 /** @var StreamInterface */
17 private $stream;
18 private const BOUNDARY_CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'()+_,-./:=? ";
19 /**
20 * @param array $elements Array of associative arrays, each containing a
21 * required "name" key mapping to the form field,
22 * name, a required "contents" key mapping to any
23 * non-array value accepted by Utils::streamFor()
24 * (non-string scalar field values are cast to
25 * string), or an array for nested expansion.
26 * Optional keys include "headers" (associative
27 * array of custom headers) and "filename" (string
28 * to send as the filename in the part).
29 * When "contents" is an array, it is recursively
30 * expanded into multiple fields using bracket notation
31 * (e.g., name[0][key]). Empty arrays produce no fields.
32 * The "filename" and "headers" options cannot be used
33 * with array contents.
34 * @param string|null $boundary You can optionally provide a specific boundary
35 *
36 * @throws \InvalidArgumentException
37 */
38 public function __construct(array $elements = [], ?string $boundary = null)
39 {
40 if ($boundary !== null && !self::isValidBoundary($boundary)) {
41 \YoastSEO_Vendor\trigger_deprecation('guzzlehttp/psr7', '2.11', 'Passing an invalid multipart boundary to MultipartStream::__construct() is deprecated; guzzlehttp/psr7 3.0 rejects invalid multipart boundaries.');
42 }
43 $this->boundary = $boundary ?: \bin2hex(\random_bytes(20));
44 $this->stream = $this->createStream($elements);
45 }
46 public function getBoundary() : string
47 {
48 return $this->boundary;
49 }
50 public function isWritable() : bool
51 {
52 return \false;
53 }
54 /**
55 * Get the headers needed before transferring the content of a POST file
56 *
57 * @param array<array-key, string> $headers
58 */
59 private function getHeaders(array $headers) : string
60 {
61 $str = '';
62 foreach ($headers as $key => $value) {
63 $key = (string) $key;
64 $str .= "{$key}: {$value}\r\n";
65 }
66 return "--{$this->boundary}\r\n" . \trim($str, " \n\r\t\x00\v") . "\r\n\r\n";
67 }
68 /**
69 * Create the aggregate stream that will be used to upload the POST data
70 */
71 protected function createStream(array $elements = []) : \YoastSEO_Vendor\Psr\Http\Message\StreamInterface
72 {
73 $stream = new \YoastSEO_Vendor\GuzzleHttp\Psr7\AppendStream();
74 foreach ($elements as $element) {
75 if (!\is_array($element)) {
76 throw new \UnexpectedValueException('An array is expected');
77 }
78 $this->addElement($stream, $element);
79 }
80 // Add the trailing boundary with CRLF
81 $stream->addStream(\YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::streamFor("--{$this->boundary}--\r\n"));
82 return $stream;
83 }
84 private function addElement(\YoastSEO_Vendor\GuzzleHttp\Psr7\AppendStream $stream, array $element) : void
85 {
86 foreach (['contents', 'name'] as $key) {
87 if (!\array_key_exists($key, $element)) {
88 throw new \InvalidArgumentException("A '{$key}' key is required");
89 }
90 }
91 if (!\is_string($element['name']) && !\is_int($element['name'])) {
92 throw new \InvalidArgumentException("The 'name' key must be a string or integer");
93 }
94 if (\is_array($element['contents'])) {
95 if (\array_key_exists('filename', $element) || \array_key_exists('headers', $element)) {
96 throw new \InvalidArgumentException("The 'filename' and 'headers' options cannot be used when 'contents' is an array");
97 }
98 $this->addNestedElements($stream, $element['contents'], (string) $element['name']);
99 return;
100 }
101 $contents = $element['contents'];
102 if (\is_scalar($contents) && !\is_string($contents)) {
103 // Multipart field values are byte strings on the wire, so finite
104 // numeric and boolean field values are cast to string here rather
105 // than tripping streamFor()'s non-string-scalar deprecation. Non-finite
106 // floats are deprecated and normalized here too, so the deprecation is
107 // reported against MultipartStream instead of transitively through
108 // streamFor().
109 if (\is_float($contents) && !\is_finite($contents)) {
110 \YoastSEO_Vendor\trigger_deprecation('guzzlehttp/psr7', '2.12', 'Passing a non-finite float as multipart contents is deprecated; guzzlehttp/psr7 3.0 rejects non-finite floats.');
111 $contents = \is_nan($contents) ? 'NAN' : ($contents > 0 ? 'INF' : '-INF');
112 }
113 $contents = (string) $contents;
114 }
115 $element['contents'] = \YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::streamFor($contents);
116 if (empty($element['filename'])) {
117 $uri = $element['contents']->getMetadata('uri');
118 if ($uri && \is_string($uri) && \substr($uri, 0, 6) !== 'php://' && \substr($uri, 0, 7) !== 'data://') {
119 $element['filename'] = $uri;
120 }
121 }
122 [$body, $headers] = $this->createElement((string) $element['name'], $element['contents'], $element['filename'] ?? null, $element['headers'] ?? []);
123 $stream->addStream(\YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::streamFor($this->getHeaders($headers)));
124 $stream->addStream($body);
125 $stream->addStream(\YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::streamFor("\r\n"));
126 }
127 /**
128 * Recursively expand array contents into multiple form fields.
129 *
130 * @param array<array-key, mixed> $contents
131 */
132 private function addNestedElements(\YoastSEO_Vendor\GuzzleHttp\Psr7\AppendStream $stream, array $contents, string $root) : void
133 {
134 foreach ($contents as $key => $value) {
135 $fieldName = $root === '' ? \sprintf('[%s]', (string) $key) : \sprintf('%s[%s]', $root, (string) $key);
136 if (\is_array($value)) {
137 $this->addNestedElements($stream, $value, $fieldName);
138 } else {
139 $this->addElement($stream, ['name' => $fieldName, 'contents' => $value]);
140 }
141 }
142 }
143 /**
144 * @param array<array-key, mixed> $headers
145 *
146 * @return array{0: StreamInterface, 1: array<array-key, string>}
147 */
148 private function createElement(string $name, \YoastSEO_Vendor\Psr\Http\Message\StreamInterface $stream, ?string $filename, array $headers) : array
149 {
150 $headers = self::normalizePartHeaders($headers);
151 // Set a default content-disposition header if one was no provided
152 $disposition = self::getHeader($headers, 'content-disposition');
153 if (!$disposition) {
154 $headers['Content-Disposition'] = $filename === '0' || $filename ? \sprintf('form-data; name="%s"; filename="%s"', $name, \basename($filename)) : "form-data; name=\"{$name}\"";
155 }
156 // Set a default content-length header if one was no provided
157 $length = self::getHeader($headers, 'content-length');
158 if (!$length) {
159 if ($length = $stream->getSize()) {
160 $headers['Content-Length'] = (string) $length;
161 }
162 }
163 // Set a default Content-Type if one was not supplied
164 $type = self::getHeader($headers, 'content-type');
165 if (!$type && ($filename === '0' || $filename)) {
166 $headers['Content-Type'] = \YoastSEO_Vendor\GuzzleHttp\Psr7\MimeType::fromFilename($filename) ?? 'application/octet-stream';
167 }
168 return [$stream, $headers];
169 }
170 /**
171 * @param array<array-key, string> $headers
172 */
173 private static function getHeader(array $headers, string $key) : ?string
174 {
175 $lowercaseHeader = \YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::asciiToLower($key);
176 foreach ($headers as $k => $v) {
177 if (\YoastSEO_Vendor\GuzzleHttp\Psr7\Utils::asciiToLower((string) $k) === $lowercaseHeader) {
178 return $v;
179 }
180 }
181 return null;
182 }
183 private static function isValidBoundary(string $boundary) : bool
184 {
185 $length = \strlen($boundary);
186 if ($length < 1 || $length > 70 || $boundary[$length - 1] === ' ') {
187 return \false;
188 }
189 return \strspn($boundary, self::BOUNDARY_CHARS) === $length;
190 }
191 /**
192 * @param array<array-key, mixed> $headers
193 *
194 * @return array<array-key, string>
195 */
196 private static function normalizePartHeaders(array $headers) : array
197 {
198 $normalized = [];
199 foreach ($headers as $key => $value) {
200 self::deprecateInvalidPartHeaderName((string) $key);
201 if (!\is_string($value)) {
202 if (!\is_scalar($value) && $value !== null && !(\is_object($value) && \method_exists($value, '__toString'))) {
203 throw new \InvalidArgumentException(\sprintf('Multipart part header value must be a string or stringable value but %s provided.', \get_debug_type($value)));
204 }
205 \YoastSEO_Vendor\trigger_deprecation('guzzlehttp/psr7', '2.11', 'Passing %s as a multipart part header value is deprecated; guzzlehttp/psr7 3.0 requires string multipart part header values.', \get_debug_type($value));
206 }
207 $value = (string) $value;
208 self::deprecateInvalidPartHeaderValue($value);
209 $normalized[$key] = $value;
210 }
211 return $normalized;
212 }
213 private static function deprecateInvalidPartHeaderName(string $name) : void
214 {
215 if (!\preg_match('/^[a-zA-Z0-9\'`#$%&*+.^_|~!-]+$/D', $name)) {
216 \YoastSEO_Vendor\trigger_deprecation('guzzlehttp/psr7', '2.11', 'Passing an invalid multipart part header name to MultipartStream is deprecated; guzzlehttp/psr7 3.0 rejects invalid multipart part header names.');
217 }
218 }
219 private static function deprecateInvalidPartHeaderValue(string $value) : void
220 {
221 if (!\preg_match('/^[\\x20\\x09\\x21-\\x7E\\x80-\\xFF]*$/D', $value)) {
222 \YoastSEO_Vendor\trigger_deprecation('guzzlehttp/psr7', '2.11', 'Passing an invalid multipart part header value to MultipartStream is deprecated; guzzlehttp/psr7 3.0 rejects invalid multipart part header values.');
223 }
224 }
225 }
226