HttplugClient.php 12 KB

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