Debian Codegraph @

lib/3rdParty/composer/symfony/http-client/Response/MockResponse.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\HttpClient\Response;
13
14 use Symfony\Component\HttpClient\Chunk\ErrorChunk;
15 use Symfony\Component\HttpClient\Chunk\FirstChunk;
16 use Symfony\Component\HttpClient\Exception\InvalidArgumentException;
17 use Symfony\Component\HttpClient\Exception\TransportException;
18 use Symfony\Component\HttpClient\Internal\ClientState;
19 use Symfony\Contracts\HttpClient\ResponseInterface;
20
21 /**
22 * A test-friendly response.
23 *
24 * @author Nicolas Grekas <[email protected]>
25 */
26 class MockResponse implements ResponseInterface, StreamableInterface
27 {
28 use CommonResponseTrait;
29 use TransportResponseTrait;
30
31 private string|iterable|null $body;
32 private array $requestOptions = [];
33 private string $requestUrl;
34 private string $requestMethod;
35
36 private static ClientState $mainMulti;
37 private static int $idSequence = 0;
38
39 /**
40 * @param string|iterable<string|\Throwable> $body The response body as a string or an iterable of strings,
41 * yielding an empty string simulates an idle timeout,
42 * throwing or yielding an exception yields an ErrorChunk
43 *
44 * @see ResponseInterface::getInfo() for possible info, e.g. "response_headers"
45 */
46 public function __construct(string|iterable $body = '', array $info = [])
47 {
48 $this->body = $body;
49 $this->info = $info + ['http_code' => 200] + $this->info;
50
51 if (!isset($info['response_headers'])) {
52 return;
53 }
54
55 $responseHeaders = [];
56
57 foreach ($info['response_headers'] as $k => $v) {
58 foreach ((array) $v as $v) {
59 $responseHeaders[] = (\is_string($k) ? $k.': ' : '').$v;
60 }
61 }
62
63 $this->info['response_headers'] = [];
64 self::addResponseHeaders($responseHeaders, $this->info, $this->headers);
65 }
66
67 public static function fromFile(string $path, array $info = []): static
68 {
69 if (!is_file($path)) {
70 throw new \InvalidArgumentException(\sprintf('File not found: "%s".', $path));
71 }
72
73 return new static(file_get_contents($path), $info);
74 }
75
76 /**
77 * Returns the options used when doing the request.
78 */
79 public function getRequestOptions(): array
80 {
81 return $this->requestOptions;
82 }
83
84 /**
85 * Returns the URL used when doing the request.
86 */
87 public function getRequestUrl(): string
88 {
89 return $this->requestUrl;
90 }
91
92 /**
93 * Returns the method used when doing the request.
94 */
95 public function getRequestMethod(): string
96 {
97 return $this->requestMethod;
98 }
99
100 public function getInfo(?string $type = null): mixed
101 {
102 return null !== $type ? $this->info[$type] ?? null : $this->info;
103 }
104
105 public function cancel(): void
106 {
107 $this->info['canceled'] = true;
108 $this->info['error'] = 'Response has been canceled.';
109 try {
110 $this->body = null;
111 } catch (TransportException $e) {
112 // ignore errors when canceling
113 }
114
115 $onProgress = $this->requestOptions['on_progress'] ?? static function () {};
116 $dlSize = isset($this->headers['content-encoding']) || 'HEAD' === ($this->info['http_method'] ?? null) || \in_array($this->info['http_code'], [204, 304], true) ? 0 : (int) ($this->headers['content-length'][0] ?? 0);
117 $onProgress($this->offset, $dlSize, $this->info);
118 }
119
120 public function __destruct()
121 {
122 $this->doDestruct();
123 }
124
125 protected function close(): void
126 {
127 $this->inflate = null;
128 $this->body = [];
129 }
130
131 /**
132 * @internal
133 */
134 public static function fromRequest(string $method, string $url, array $options, ResponseInterface $mock): self
135 {
136 $response = new self([]);
137 $response->requestOptions = $options;
138 $response->id = ++self::$idSequence;
139 $response->shouldBuffer = $options['buffer'] ?? true;
140 $response->initializer = static fn (self $response) => \is_array($response->body[0] ?? null);
141
142 $response->info['redirect_count'] = 0;
143 $response->info['redirect_url'] = null;
144 $response->info['start_time'] = microtime(true);
145 $response->info['http_method'] = $method;
146 $response->info['http_code'] = 0;
147 $response->info['user_data'] = $options['user_data'] ?? null;
148 $response->info['max_duration'] = $options['max_duration'] ?? null;
149 $response->info['url'] = $url;
150 $response->info['original_url'] = $url;
151
152 if ($mock instanceof self) {
153 $mock->requestOptions = $response->requestOptions;
154 $mock->requestMethod = $method;
155 $mock->requestUrl = $url;
156 }
157
158 self::writeRequest($response, $options, $mock);
159 $response->body[] = [$options, $mock];
160
161 return $response;
162 }
163
164 protected static function schedule(self $response, array &$runningResponses): void
165 {
166 if (!isset($response->id)) {
167 throw new InvalidArgumentException('MockResponse instances must be issued by MockHttpClient before processing.');
168 }
169
170 $multi = self::$mainMulti ??= new ClientState();
171
172 if (!isset($runningResponses[0])) {
173 $runningResponses[0] = [$multi, []];
174 }
175
176 $runningResponses[0][1][$response->id] = $response;
177 }
178
179 protected static function perform(ClientState $multi, array $responses): void
180 {
181 foreach ($responses as $response) {
182 $id = $response->id;
183
184 if (null === $response->body) {
185 // Canceled response
186 $response->body = [];
187 } elseif ([] === $response->body) {
188 // Error chunk
189 $multi->handlesActivity[$id][] = null;
190 $multi->handlesActivity[$id][] = null !== $response->info['error'] ? new TransportException($response->info['error']) : null;
191 } elseif (null === $chunk = array_shift($response->body)) {
192 // Last chunk
193 $multi->handlesActivity[$id][] = null;
194 $multi->handlesActivity[$id][] = array_shift($response->body);
195 } elseif (\is_array($chunk)) {
196 // First chunk
197 try {
198 $offset = 0;
199 $chunk[1]->getStatusCode();
200 $chunk[1]->getHeaders(false);
201 self::readResponse($response, $chunk[0], $chunk[1], $offset);
202 $multi->handlesActivity[$id][] = new FirstChunk();
203 } catch (\Throwable $e) {
204 $multi->handlesActivity[$id][] = null;
205 $multi->handlesActivity[$id][] = $e;
206 }
207 } elseif ($chunk instanceof \Throwable) {
208 $multi->handlesActivity[$id][] = null;
209 $multi->handlesActivity[$id][] = $chunk;
210 } else {
211 // Data or timeout chunk
212 $multi->handlesActivity[$id][] = $chunk;
213 }
214 }
215 }
216
217 protected static function select(ClientState $multi, float $timeout): int
218 {
219 return 42;
220 }
221
222 /**
223 * Simulates sending the request.
224 */
225 private static function writeRequest(self $response, array $options, ResponseInterface $mock): void
226 {
227 $onProgress = $options['on_progress'] ?? static function () {};
228 $response->info += $mock->getInfo() ?: [];
229 if (null !== $mock->getInfo('start_time')) {
230 $response->info['start_time'] = $mock->getInfo('start_time');
231 }
232
233 // simulate "size_upload" if it is set
234 if (isset($response->info['size_upload'])) {
235 $response->info['size_upload'] = 0.0;
236 }
237
238 // simulate "total_time" if it is not set
239 if (!isset($response->info['total_time'])) {
240 $response->info['total_time'] = microtime(true) - $response->info['start_time'];
241 }
242
243 // "notify" DNS resolution
244 $onProgress(0, 0, $response->info);
245
246 // consume the request body
247 if (\is_resource($body = $options['body'] ?? '')) {
248 $data = stream_get_contents($body);
249 if (isset($response->info['size_upload'])) {
250 $response->info['size_upload'] += \strlen($data);
251 }
252 } elseif ($body instanceof \Closure) {
253 while ('' !== $data = $body(16372)) {
254 if (!\is_string($data)) {
255 throw new TransportException(\sprintf('Return value of the "body" option callback must be string, "%s" returned.', get_debug_type($data)));
256 }
257
258 // "notify" upload progress
259 if (isset($response->info['size_upload'])) {
260 $response->info['size_upload'] += \strlen($data);
261 }
262
263 $onProgress(0, 0, $response->info);
264 }
265 }
266 }
267
268 /**
269 * Simulates reading the response.
270 */
271 private static function readResponse(self $response, array $options, ResponseInterface $mock, int &$offset): void
272 {
273 $onProgress = $options['on_progress'] ?? static function () {};
274
275 // populate info related to headers
276 $info = $mock->getInfo() ?: [];
277 $response->info['http_code'] = ($info['http_code'] ?? 0) ?: $mock->getStatusCode() ?: 200;
278 $response->addResponseHeaders($info['response_headers'] ?? [], $response->info, $response->headers);
279 $dlSize = isset($response->headers['content-encoding']) || 'HEAD' === $response->info['http_method'] || \in_array($response->info['http_code'], [204, 304], true) ? 0 : (int) ($response->headers['content-length'][0] ?? 0);
280
281 $response->info = [
282 'start_time' => $response->info['start_time'],
283 'user_data' => $response->info['user_data'],
284 'max_duration' => $response->info['max_duration'],
285 'http_code' => $response->info['http_code'],
286 ] + $info + $response->info;
287
288 if (null !== $response->info['error']) {
289 throw new TransportException($response->info['error']);
290 }
291
292 if (!isset($response->info['total_time'])) {
293 $response->info['total_time'] = microtime(true) - $response->info['start_time'];
294 }
295
296 // "notify" headers arrival
297 $onProgress(0, $dlSize, $response->info);
298
299 // cast response body to activity list
300 $body = $mock instanceof self ? $mock->body : $mock->getContent(false);
301
302 if (!\is_string($body)) {
303 try {
304 foreach ($body as $chunk) {
305 if ($chunk instanceof \Throwable) {
306 throw $chunk;
307 }
308
309 if ('' === $chunk = (string) $chunk) {
310 // simulate an idle timeout
311 $response->body[] = new ErrorChunk($offset, \sprintf('Idle timeout reached for "%s".', $response->info['url']));
312 } else {
313 $response->body[] = $chunk;
314 $offset += \strlen($chunk);
315 // "notify" download progress
316 $onProgress($offset, $dlSize, $response->info);
317 }
318 }
319 } catch (\Throwable $e) {
320 $response->body[] = $e;
321 }
322 } elseif ('' !== $body) {
323 $response->body[] = $body;
324 $offset = \strlen($body);
325 }
326
327 if (!isset($response->info['total_time'])) {
328 $response->info['total_time'] = microtime(true) - $response->info['start_time'];
329 }
330
331 // "notify" completion
332 $onProgress($offset, $dlSize, $response->info);
333
334 if ($dlSize && $offset !== $dlSize) {
335 throw new TransportException(\sprintf('Transfer closed with %d bytes remaining to read.', $dlSize - $offset));
336 }
337 }
338 }