Debian Codegraph @

lib/3rdParty/composer/symfony/http-client/HttplugClient.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;
13
14 use GuzzleHttp\Promise\Promise as GuzzlePromise;
15 use GuzzleHttp\Promise\RejectedPromise;
16 use GuzzleHttp\Promise\Utils;
17 use Http\Client\Exception\NetworkException;
18 use Http\Client\Exception\RequestException;
19 use Http\Client\HttpAsyncClient;
20 use Http\Discovery\Psr17Factory;
21 use Http\Discovery\Psr17FactoryDiscovery;
22 use Nyholm\Psr7\Factory\Psr17Factory as NyholmPsr17Factory;
23 use Nyholm\Psr7\Request;
24 use Nyholm\Psr7\Uri;
25 use Psr\Http\Client\ClientInterface;
26 use Psr\Http\Message\RequestFactoryInterface;
27 use Psr\Http\Message\RequestInterface;
28 use Psr\Http\Message\ResponseFactoryInterface;
29 use Psr\Http\Message\ResponseInterface as Psr7ResponseInterface;
30 use Psr\Http\Message\StreamFactoryInterface;
31 use Psr\Http\Message\StreamInterface;
32 use Psr\Http\Message\UriFactoryInterface;
33 use Psr\Http\Message\UriInterface;
34 use Symfony\Component\HttpClient\Internal\HttplugWaitLoop;
35 use Symfony\Component\HttpClient\Response\HttplugPromise;
36 use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
37 use Symfony\Contracts\HttpClient\HttpClientInterface;
38 use Symfony\Contracts\HttpClient\ResponseInterface;
39 use Symfony\Contracts\Service\ResetInterface;
40
41 if (!interface_exists(HttpAsyncClient::class)) {
42 throw new \LogicException('You cannot use "Symfony\Component\HttpClient\HttplugClient" as the "php-http/httplug" package is not installed. Try running "composer require php-http/discovery php-http/async-client-implementation:*".');
43 }
44
45 if (!interface_exists(RequestFactoryInterface::class)) {
46 throw new \LogicException('You cannot use the "Symfony\Component\HttpClient\HttplugClient" as the "psr/http-factory" package is not installed. Try running "composer require php-http/discovery psr/http-factory-implementation:*".');
47 }
48
49 /**
50 * An adapter to turn a Symfony HttpClientInterface into an Httplug client.
51 *
52 * In comparison to Psr18Client, this client supports asynchronous requests.
53 *
54 * Run "composer require php-http/discovery php-http/async-client-implementation:*"
55 * to get the required dependencies.
56 *
57 * @author Nicolas Grekas <[email protected]>
58 */
59 final class HttplugClient implements ClientInterface, HttpAsyncClient, RequestFactoryInterface, StreamFactoryInterface, UriFactoryInterface, ResetInterface
60 {
61 private HttpClientInterface $client;
62 private ResponseFactoryInterface $responseFactory;
63 private StreamFactoryInterface $streamFactory;
64 private bool $autoUpgradeHttpVersion = true;
65
66 /**
67 * @var \SplObjectStorage<ResponseInterface, array{RequestInterface, Promise}>|null
68 */
69 private ?\SplObjectStorage $promisePool;
70
71 private HttplugWaitLoop $waitLoop;
72
73 public function __construct(?HttpClientInterface $client = null, ?ResponseFactoryInterface $responseFactory = null, ?StreamFactoryInterface $streamFactory = null)
74 {
75 $this->client = $client ?? HttpClient::create();
76 $streamFactory ??= $responseFactory instanceof StreamFactoryInterface ? $responseFactory : null;
77 $this->promisePool = class_exists(Utils::class) ? new \SplObjectStorage() : null;
78
79 if (null === $responseFactory || null === $streamFactory) {
80 if (class_exists(Psr17Factory::class)) {
81 $psr17Factory = new Psr17Factory();
82 } elseif (class_exists(NyholmPsr17Factory::class)) {
83 $psr17Factory = new NyholmPsr17Factory();
84 } else {
85 throw new \LogicException('You cannot use the "Symfony\Component\HttpClient\HttplugClient" as no PSR-17 factories have been provided. Try running "composer require php-http/discovery psr/http-factory-implementation:*".');
86 }
87
88 $responseFactory ??= $psr17Factory;
89 $streamFactory ??= $psr17Factory;
90 }
91
92 $this->responseFactory = $responseFactory;
93 $this->streamFactory = $streamFactory;
94 $this->waitLoop = new HttplugWaitLoop($this->client, $this->promisePool, $this->responseFactory, $this->streamFactory);
95 }
96
97 public function withOptions(array $options): static
98 {
99 $clone = clone $this;
100 if (\array_key_exists('auto_upgrade_http_version', $options)) {
101 $clone->autoUpgradeHttpVersion = $options['auto_upgrade_http_version'];
102 unset($options['auto_upgrade_http_version']);
103 }
104 $clone->client = $clone->client->withOptions($options);
105
106 return $clone;
107 }
108
109 public function sendRequest(RequestInterface $request): Psr7ResponseInterface
110 {
111 try {
112 return HttplugWaitLoop::createPsr7Response($this->responseFactory, $this->streamFactory, $this->client, $this->sendPsr7Request($request), true);
113 } catch (TransportExceptionInterface $e) {
114 throw new NetworkException($e->getMessage(), $request, $e);
115 }
116 }
117
118 public function sendAsyncRequest(RequestInterface $request): HttplugPromise
119 {
120 if (!$promisePool = $this->promisePool) {
121 throw new \LogicException(\sprintf('You cannot use "%s()" as the "guzzlehttp/promises" package is not installed. Try running "composer require guzzlehttp/promises".', __METHOD__));
122 }
123
124 try {
125 $response = $this->sendPsr7Request($request, true);
126 } catch (NetworkException $e) {
127 return new HttplugPromise(new RejectedPromise($e));
128 }
129
130 $waitLoop = $this->waitLoop;
131
132 $promise = new GuzzlePromise(static function () use ($response, $waitLoop) {
133 $waitLoop->wait($response);
134 }, static function () use ($response, $promisePool) {
135 $response->cancel();
136 unset($promisePool[$response]);
137 });
138
139 $promisePool[$response] = [$request, $promise];
140
141 return new HttplugPromise($promise);
142 }
143
144 /**
145 * Resolves pending promises that complete before the timeouts are reached.
146 *
147 * When $maxDuration is null and $idleTimeout is reached, promises are rejected.
148 *
149 * @return int The number of remaining pending promises
150 */
151 public function wait(?float $maxDuration = null, ?float $idleTimeout = null): int
152 {
153 return $this->waitLoop->wait(null, $maxDuration, $idleTimeout);
154 }
155
156 /**
157 * @param UriInterface|string $uri
158 */
159 public function createRequest(string $method, $uri = ''): RequestInterface
160 {
161 if ($this->responseFactory instanceof RequestFactoryInterface) {
162 $request = $this->responseFactory->createRequest($method, $uri);
163 } elseif (class_exists(Psr17FactoryDiscovery::class)) {
164 $request = Psr17FactoryDiscovery::findRequestFactory()->createRequest($method, $uri);
165 } elseif (class_exists(Request::class)) {
166 $request = new Request($method, $uri);
167 } else {
168 throw new \LogicException(\sprintf('You cannot use "%s()" as no PSR-17 factories have been found. Try running "composer require php-http/discovery psr/http-factory-implementation:*".', __METHOD__));
169 }
170
171 return $request;
172 }
173
174 public function createStream(string $content = ''): StreamInterface
175 {
176 return $this->streamFactory->createStream($content);
177 }
178
179 public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface
180 {
181 return $this->streamFactory->createStreamFromFile($filename, $mode);
182 }
183
184 public function createStreamFromResource($resource): StreamInterface
185 {
186 return $this->streamFactory->createStreamFromResource($resource);
187 }
188
189 public function createUri(string $uri = ''): UriInterface
190 {
191 if ($this->responseFactory instanceof UriFactoryInterface) {
192 return $this->responseFactory->createUri($uri);
193 }
194
195 if (class_exists(Psr17FactoryDiscovery::class)) {
196 return Psr17FactoryDiscovery::findUriFactory()->createUri($uri);
197 }
198
199 if (class_exists(Uri::class)) {
200 return new Uri($uri);
201 }
202
203 throw new \LogicException(\sprintf('You cannot use "%s()" as no PSR-17 factories have been found. Try running "composer require php-http/discovery psr/http-factory-implementation:*".', __METHOD__));
204 }
205
206 public function __serialize(): array
207 {
208 throw new \BadMethodCallException('Cannot serialize '.__CLASS__);
209 }
210
211 public function __unserialize(array $data): void
212 {
213 throw new \BadMethodCallException('Cannot unserialize '.__CLASS__);
214 }
215
216 public function __destruct()
217 {
218 $this->wait();
219 }
220
221 public function reset(): void
222 {
223 if ($this->client instanceof ResetInterface) {
224 $this->client->reset();
225 }
226 }
227
228 private function sendPsr7Request(RequestInterface $request, ?bool $buffer = null): ResponseInterface
229 {
230 try {
231 $body = $request->getBody();
232 $headers = $request->getHeaders();
233
234 $size = $request->getHeader('content-length')[0] ?? -1;
235 if (0 > $size && 0 < $size = $body->getSize() ?? -1) {
236 $headers['Content-Length'] = [$size];
237 }
238
239 if (0 === $size) {
240 $body = '';
241 } elseif (0 < $size && $size < 1 << 21) {
242 if ($body->isSeekable()) {
243 try {
244 $body->seek(0);
245 } catch (\RuntimeException) {
246 // ignore
247 }
248 }
249
250 $body = $body->getContents();
251 } else {
252 $body = static function (int $size) use ($body) {
253 if ($body->isSeekable()) {
254 try {
255 $body->seek(0);
256 } catch (\RuntimeException) {
257 // ignore
258 }
259 }
260
261 while (!$body->eof()) {
262 yield $body->read($size);
263 }
264 };
265 }
266
267 $options = [
268 'headers' => $headers,
269 'body' => $body,
270 'buffer' => $buffer,
271 ];
272
273 if (!$this->autoUpgradeHttpVersion || '1.0' === $request->getProtocolVersion()) {
274 $options['http_version'] = $request->getProtocolVersion();
275 }
276
277 return $this->client->request($request->getMethod(), (string) $request->getUri(), $options);
278 } catch (\InvalidArgumentException $e) {
279 throw new RequestException($e->getMessage(), $request, $e);
280 } catch (TransportExceptionInterface $e) {
281 throw new NetworkException($e->getMessage(), $request, $e);
282 }
283 }
284 }