CachingHttpClient.php 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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 Symfony\Component\HttpClient\Response\MockResponse;
  12. use Symfony\Component\HttpClient\Response\ResponseStream;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpKernel\HttpCache\HttpCache;
  15. use Symfony\Component\HttpKernel\HttpCache\StoreInterface;
  16. use Symfony\Component\HttpKernel\HttpClientKernel;
  17. use Symfony\Contracts\HttpClient\HttpClientInterface;
  18. use Symfony\Contracts\HttpClient\ResponseInterface;
  19. use Symfony\Contracts\HttpClient\ResponseStreamInterface;
  20. use Symfony\Contracts\Service\ResetInterface;
  21. /**
  22. * Adds caching on top of an HTTP client.
  23. *
  24. * The implementation buffers responses in memory and doesn't stream directly from the network.
  25. * You can disable/enable this layer by setting option "no_cache" under "extra" to true/false.
  26. * By default, caching is enabled unless the "buffer" option is set to false.
  27. *
  28. * @author Nicolas Grekas <p@tchwork.com>
  29. */
  30. class CachingHttpClient implements HttpClientInterface, ResetInterface
  31. {
  32. use HttpClientTrait;
  33. /**
  34. * @var \Symfony\Contracts\HttpClient\HttpClientInterface
  35. */
  36. private $client;
  37. /**
  38. * @var \Symfony\Component\HttpKernel\HttpCache\HttpCache
  39. */
  40. private $cache;
  41. /**
  42. * @var mixed[]
  43. */
  44. private $defaultOptions = self::OPTIONS_DEFAULTS;
  45. /**
  46. * @param \Symfony\Contracts\HttpClient\HttpClientInterface $client
  47. * @param \Symfony\Component\HttpKernel\HttpCache\StoreInterface $store
  48. * @param mixed[] $defaultOptions
  49. */
  50. public function __construct($client, $store, $defaultOptions = [])
  51. {
  52. if (!class_exists(HttpClientKernel::class)) {
  53. throw new \LogicException(sprintf('Using "%s" requires that the HttpKernel component version 4.3 or higher is installed, try running "composer require symfony/http-kernel:^5.4".', __CLASS__));
  54. }
  55. $this->client = $client;
  56. $kernel = new HttpClientKernel($client);
  57. $this->cache = new HttpCache($kernel, $store, null, $defaultOptions);
  58. unset($defaultOptions['debug']);
  59. unset($defaultOptions['default_ttl']);
  60. unset($defaultOptions['private_headers']);
  61. unset($defaultOptions['skip_response_headers']);
  62. unset($defaultOptions['allow_reload']);
  63. unset($defaultOptions['allow_revalidate']);
  64. unset($defaultOptions['stale_while_revalidate']);
  65. unset($defaultOptions['stale_if_error']);
  66. unset($defaultOptions['trace_level']);
  67. unset($defaultOptions['trace_header']);
  68. if ($defaultOptions) {
  69. [, $this->defaultOptions] = self::prepareRequest(null, null, $defaultOptions, $this->defaultOptions);
  70. }
  71. }
  72. /**
  73. * @param string $method
  74. * @param string $url
  75. * @param mixed[] $options
  76. */
  77. public function request($method, $url, $options = [])
  78. {
  79. [$url, $options] = $this->prepareRequest($method, $url, $options, $this->defaultOptions, true);
  80. $url = implode('', $url);
  81. if (!empty($options['body']) || !empty($options['extra']['no_cache']) || !\in_array($method, ['GET', 'HEAD', 'OPTIONS'])) {
  82. return $this->client->request($method, $url, $options);
  83. }
  84. $request = Request::create($url, $method);
  85. $request->attributes->set('http_client_options', $options);
  86. foreach ($options['normalized_headers'] as $name => $values) {
  87. if ('cookie' !== $name) {
  88. foreach ($values as $value) {
  89. $request->headers->set($name, substr($value, 2 + \strlen($name)), false);
  90. }
  91. continue;
  92. }
  93. foreach ($values as $cookies) {
  94. foreach (explode('; ', substr($cookies, \strlen('Cookie: '))) as $cookie) {
  95. if ('' !== $cookie) {
  96. $cookie = explode('=', $cookie, 2);
  97. $request->cookies->set($cookie[0], $cookie[1] ?? '');
  98. }
  99. }
  100. }
  101. }
  102. $response = $this->cache->handle($request);
  103. $response = new MockResponse($response->getContent(), [
  104. 'http_code' => $response->getStatusCode(),
  105. 'response_headers' => $response->headers->allPreserveCase(),
  106. ]);
  107. return MockResponse::fromRequest($method, $url, $options, $response);
  108. }
  109. /**
  110. * @param \Symfony\Contracts\HttpClient\ResponseInterface|mixed[] $responses
  111. * @param float|null $timeout
  112. */
  113. public function stream($responses, $timeout = null)
  114. {
  115. if ($responses instanceof ResponseInterface) {
  116. $responses = [$responses];
  117. }
  118. $mockResponses = [];
  119. $clientResponses = [];
  120. foreach ($responses as $response) {
  121. if ($response instanceof MockResponse) {
  122. $mockResponses[] = $response;
  123. } else {
  124. $clientResponses[] = $response;
  125. }
  126. }
  127. if (!$mockResponses) {
  128. return $this->client->stream($clientResponses, $timeout);
  129. }
  130. if (!$clientResponses) {
  131. return new ResponseStream(MockResponse::stream($mockResponses, $timeout));
  132. }
  133. return new ResponseStream((function () use ($mockResponses, $clientResponses, $timeout) {
  134. yield from MockResponse::stream($mockResponses, $timeout);
  135. yield $this->client->stream($clientResponses, $timeout);
  136. })());
  137. }
  138. /**
  139. * @return void
  140. */
  141. public function reset()
  142. {
  143. if ($this->client instanceof ResetInterface) {
  144. $this->client->reset();
  145. }
  146. }
  147. }