Debian Codegraph @

lib/3rdParty/composer/guzzlehttp/psr7/src/MultipartStream.php

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