PageRenderTime 32ms CodeModel.GetById 1ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php

https://gitlab.com/ealexis.t/trends
PHP | 197 lines | 132 code | 26 blank | 39 comment | 16 complexity | dc20cc9837a45e56607bbcb5d89024fa MD5 | raw file
  1. <?php
  2. namespace GuzzleHttp\Handler;
  3. use GuzzleHttp\Promise as P;
  4. use GuzzleHttp\Promise\Promise;
  5. use GuzzleHttp\Psr7;
  6. use Psr\Http\Message\RequestInterface;
  7. /**
  8. * Returns an asynchronous response using curl_multi_* functions.
  9. *
  10. * When using the CurlMultiHandler, custom curl options can be specified as an
  11. * associative array of curl option constants mapping to values in the
  12. * **curl** key of the provided request options.
  13. *
  14. * @property resource $_mh Internal use only. Lazy loaded multi-handle.
  15. */
  16. class CurlMultiHandler
  17. {
  18. /** @var CurlFactoryInterface */
  19. private $factory;
  20. private $selectTimeout;
  21. private $active;
  22. private $handles = [];
  23. private $delays = [];
  24. /**
  25. * This handler accepts the following options:
  26. *
  27. * - handle_factory: An optional factory used to create curl handles
  28. * - select_timeout: Optional timeout (in seconds) to block before timing
  29. * out while selecting curl handles. Defaults to 1 second.
  30. *
  31. * @param array $options
  32. */
  33. public function __construct(array $options = [])
  34. {
  35. $this->factory = isset($options['handle_factory'])
  36. ? $options['handle_factory'] : new CurlFactory(50);
  37. $this->selectTimeout = isset($options['select_timeout'])
  38. ? $options['select_timeout'] : 1;
  39. }
  40. public function __get($name)
  41. {
  42. if ($name === '_mh') {
  43. return $this->_mh = curl_multi_init();
  44. }
  45. throw new \BadMethodCallException();
  46. }
  47. public function __destruct()
  48. {
  49. if (isset($this->_mh)) {
  50. curl_multi_close($this->_mh);
  51. unset($this->_mh);
  52. }
  53. }
  54. public function __invoke(RequestInterface $request, array $options)
  55. {
  56. $easy = $this->factory->create($request, $options);
  57. $id = (int) $easy->handle;
  58. $promise = new Promise(
  59. [$this, 'execute'],
  60. function () use ($id) { return $this->cancel($id); }
  61. );
  62. $this->addRequest(['easy' => $easy, 'deferred' => $promise]);
  63. return $promise;
  64. }
  65. /**
  66. * Ticks the curl event loop.
  67. */
  68. public function tick()
  69. {
  70. // Add any delayed handles if needed.
  71. if ($this->delays) {
  72. $currentTime = microtime(true);
  73. foreach ($this->delays as $id => $delay) {
  74. if ($currentTime >= $delay) {
  75. unset($this->delays[$id]);
  76. curl_multi_add_handle(
  77. $this->_mh,
  78. $this->handles[$id]['easy']->handle
  79. );
  80. }
  81. }
  82. }
  83. // Step through the task queue which may add additional requests.
  84. P\queue()->run();
  85. if ($this->active &&
  86. curl_multi_select($this->_mh, $this->selectTimeout) === -1
  87. ) {
  88. // Perform a usleep if a select returns -1.
  89. // See: https://bugs.php.net/bug.php?id=61141
  90. usleep(250);
  91. }
  92. while (curl_multi_exec($this->_mh, $this->active) === CURLM_CALL_MULTI_PERFORM);
  93. $this->processMessages();
  94. }
  95. /**
  96. * Runs until all outstanding connections have completed.
  97. */
  98. public function execute()
  99. {
  100. $queue = P\queue();
  101. while ($this->handles || !$queue->isEmpty()) {
  102. // If there are no transfers, then sleep for the next delay
  103. if (!$this->active && $this->delays) {
  104. usleep($this->timeToNext());
  105. }
  106. $this->tick();
  107. }
  108. }
  109. private function addRequest(array $entry)
  110. {
  111. $easy = $entry['easy'];
  112. $id = (int) $easy->handle;
  113. $this->handles[$id] = $entry;
  114. if (empty($easy->options['delay'])) {
  115. curl_multi_add_handle($this->_mh, $easy->handle);
  116. } else {
  117. $this->delays[$id] = microtime(true) + ($easy->options['delay'] / 1000);
  118. }
  119. }
  120. /**
  121. * Cancels a handle from sending and removes references to it.
  122. *
  123. * @param int $id Handle ID to cancel and remove.
  124. *
  125. * @return bool True on success, false on failure.
  126. */
  127. private function cancel($id)
  128. {
  129. // Cannot cancel if it has been processed.
  130. if (!isset($this->handles[$id])) {
  131. return false;
  132. }
  133. $handle = $this->handles[$id]['easy']->handle;
  134. unset($this->delays[$id], $this->handles[$id]);
  135. curl_multi_remove_handle($this->_mh, $handle);
  136. curl_close($handle);
  137. return true;
  138. }
  139. private function processMessages()
  140. {
  141. while ($done = curl_multi_info_read($this->_mh)) {
  142. $id = (int) $done['handle'];
  143. curl_multi_remove_handle($this->_mh, $done['handle']);
  144. if (!isset($this->handles[$id])) {
  145. // Probably was cancelled.
  146. continue;
  147. }
  148. $entry = $this->handles[$id];
  149. unset($this->handles[$id], $this->delays[$id]);
  150. $entry['easy']->errno = $done['result'];
  151. $entry['deferred']->resolve(
  152. CurlFactory::finish(
  153. $this,
  154. $entry['easy'],
  155. $this->factory
  156. )
  157. );
  158. }
  159. }
  160. private function timeToNext()
  161. {
  162. $currentTime = microtime(true);
  163. $nextTime = PHP_INT_MAX;
  164. foreach ($this->delays as $time) {
  165. if ($time < $nextTime) {
  166. $nextTime = $time;
  167. }
  168. }
  169. return max(0, $nextTime - $currentTime) * 1000000;
  170. }
  171. }