AsyncContext.php 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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\Response;
  11. use Symfony\Component\HttpClient\Chunk\DataChunk;
  12. use Symfony\Component\HttpClient\Chunk\LastChunk;
  13. use Symfony\Component\HttpClient\Exception\TransportException;
  14. use Symfony\Contracts\HttpClient\ChunkInterface;
  15. use Symfony\Contracts\HttpClient\HttpClientInterface;
  16. use Symfony\Contracts\HttpClient\ResponseInterface;
  17. /**
  18. * A DTO to work with AsyncResponse.
  19. *
  20. * @author Nicolas Grekas <p@tchwork.com>
  21. */
  22. final class AsyncContext
  23. {
  24. private $passthru;
  25. /**
  26. * @var \Symfony\Contracts\HttpClient\HttpClientInterface
  27. */
  28. private $client;
  29. /**
  30. * @var \Symfony\Contracts\HttpClient\ResponseInterface
  31. */
  32. private $response;
  33. /**
  34. * @var mixed[]
  35. */
  36. private $info = [];
  37. private $content;
  38. /**
  39. * @var int
  40. */
  41. private $offset;
  42. /**
  43. * @param resource|null $content
  44. * @param callable|null $passthru
  45. * @param \Symfony\Contracts\HttpClient\HttpClientInterface $client
  46. * @param \Symfony\Contracts\HttpClient\ResponseInterface $response
  47. * @param mixed[] $info
  48. * @param int $offset
  49. */
  50. public function __construct(&$passthru, $client, &$response, &$info, $content, $offset)
  51. {
  52. $this->passthru = &$passthru;
  53. $this->client = $client;
  54. $this->response = &$response;
  55. $this->info = &$info;
  56. $this->content = $content;
  57. $this->offset = $offset;
  58. }
  59. /**
  60. * Returns the HTTP status without consuming the response.
  61. */
  62. public function getStatusCode()
  63. {
  64. return $this->response->getInfo('http_code');
  65. }
  66. /**
  67. * Returns the headers without consuming the response.
  68. */
  69. public function getHeaders()
  70. {
  71. $headers = [];
  72. foreach ($this->response->getInfo('response_headers') as $h) {
  73. if (11 <= \strlen($h) && '/' === $h[4] && preg_match('#^HTTP/\d+(?:\.\d+)? ([123456789]\d\d)(?: |$)#', $h, $m)) {
  74. $headers = [];
  75. } elseif (2 === \count($m = explode(':', $h, 2))) {
  76. $headers[strtolower($m[0])][] = ltrim($m[1]);
  77. }
  78. }
  79. return $headers;
  80. }
  81. /**
  82. * @return resource|null The PHP stream resource where the content is buffered, if it is
  83. */
  84. public function getContent()
  85. {
  86. return $this->content;
  87. }
  88. /**
  89. * Creates a new chunk of content.
  90. */
  91. public function createChunk(string $data)
  92. {
  93. return new DataChunk($this->offset, $data);
  94. }
  95. /**
  96. * Pauses the request for the given number of seconds.
  97. */
  98. public function pause(float $duration)
  99. {
  100. if (\is_callable($pause = $this->response->getInfo('pause_handler'))) {
  101. $pause($duration);
  102. } elseif (0 < $duration) {
  103. usleep(1E6 * $duration);
  104. }
  105. }
  106. /**
  107. * Cancels the request and returns the last chunk to yield.
  108. */
  109. public function cancel()
  110. {
  111. $this->info['canceled'] = true;
  112. $this->info['error'] = 'Response has been canceled.';
  113. $this->response->cancel();
  114. return new LastChunk();
  115. }
  116. /**
  117. * Returns the current info of the response.
  118. * @return mixed
  119. */
  120. public function getInfo(string $type = null)
  121. {
  122. if (null !== $type) {
  123. return $this->info[$type] ?? $this->response->getInfo($type);
  124. }
  125. return $this->info + $this->response->getInfo();
  126. }
  127. /**
  128. * Attaches an info to the response.
  129. *
  130. * @return $this
  131. * @param mixed $value
  132. */
  133. public function setInfo(string $type, $value)
  134. {
  135. if ('canceled' === $type && $value !== $this->info['canceled']) {
  136. throw new \LogicException('You cannot set the "canceled" info directly.');
  137. }
  138. if (null === $value) {
  139. unset($this->info[$type]);
  140. } else {
  141. $this->info[$type] = $value;
  142. }
  143. return $this;
  144. }
  145. /**
  146. * Returns the currently processed response.
  147. */
  148. public function getResponse()
  149. {
  150. return $this->response;
  151. }
  152. /**
  153. * Replaces the currently processed response by doing a new request.
  154. */
  155. public function replaceRequest(string $method, string $url, array $options = [])
  156. {
  157. $this->info['previous_info'][] = $info = $this->response->getInfo();
  158. if (null !== $onProgress = $options['on_progress'] ?? null) {
  159. $thisInfo = &$this->info;
  160. $options['on_progress'] = static function (int $dlNow, int $dlSize, array $info) use (&$thisInfo, $onProgress) {
  161. $onProgress($dlNow, $dlSize, $thisInfo + $info);
  162. };
  163. }
  164. if (0 < ($info['max_duration'] ?? 0) && 0 < ($info['total_time'] ?? 0)) {
  165. if (0 >= $options['max_duration'] = $info['max_duration'] - $info['total_time']) {
  166. throw new TransportException(sprintf('Max duration was reached for "%s".', $info['url']));
  167. }
  168. }
  169. return $this->response = $this->client->request($method, $url, ['buffer' => false] + $options);
  170. }
  171. /**
  172. * Replaces the currently processed response by another one.
  173. */
  174. public function replaceResponse(ResponseInterface $response)
  175. {
  176. $this->info['previous_info'][] = $this->response->getInfo();
  177. return $this->response = $response;
  178. }
  179. /**
  180. * Replaces or removes the chunk filter iterator.
  181. *
  182. * @param ?callable(ChunkInterface, self): ?\Iterator $passthru
  183. */
  184. public function passthru(callable $passthru = null)
  185. {
  186. $this->passthru = $passthru ?? static function ($chunk, $context) {
  187. $context->passthru = null;
  188. yield $chunk;
  189. };
  190. }
  191. }