2 namespace GuzzleHttp\Handler;
4 use GuzzleHttp\Promise as P;
5 use GuzzleHttp\Promise\Promise;
7 use Psr\Http\Message\RequestInterface;
10 * Returns an asynchronous response using curl_multi_* functions.
12 * When using the CurlMultiHandler, custom curl options can be specified as an
13 * associative array of curl option constants mapping to values in the
14 * **curl** key of the provided request options.
16 * @property resource $_mh Internal use only. Lazy loaded multi-handle.
18 class CurlMultiHandler
20 /** @var CurlFactoryInterface */
22 private $selectTimeout;
24 private $handles = [];
28 * This handler accepts the following options:
30 * - handle_factory: An optional factory used to create curl handles
31 * - select_timeout: Optional timeout (in seconds) to block before timing
32 * out while selecting curl handles. Defaults to 1 second.
34 * @param array $options
36 public function __construct(array $options = [])
38 $this->factory = isset($options['handle_factory'])
39 ? $options['handle_factory'] : new CurlFactory(50);
40 $this->selectTimeout = isset($options['select_timeout'])
41 ? $options['select_timeout'] : 1;
44 public function __get($name)
46 if ($name === '_mh') {
47 return $this->_mh = curl_multi_init();
50 throw new \BadMethodCallException();
53 public function __destruct()
55 if (isset($this->_mh)) {
56 curl_multi_close($this->_mh);
61 public function __invoke(RequestInterface $request, array $options)
63 $easy = $this->factory->create($request, $options);
64 $id = (int) $easy->handle;
66 $promise = new Promise(
68 function () use ($id) { return $this->cancel($id); }
71 $this->addRequest(['easy' => $easy, 'deferred' => $promise]);
77 * Ticks the curl event loop.
79 public function tick()
81 // Add any delayed handles if needed.
83 $currentTime = microtime(true);
84 foreach ($this->delays as $id => $delay) {
85 if ($currentTime >= $delay) {
86 unset($this->delays[$id]);
87 curl_multi_add_handle(
89 $this->handles[$id]['easy']->handle
95 // Step through the task queue which may add additional requests.
99 curl_multi_select($this->_mh, $this->selectTimeout) === -1
101 // Perform a usleep if a select returns -1.
102 // See: https://bugs.php.net/bug.php?id=61141
106 while (curl_multi_exec($this->_mh, $this->active) === CURLM_CALL_MULTI_PERFORM);
108 $this->processMessages();
112 * Runs until all outstanding connections have completed.
114 public function execute()
118 while ($this->handles || !$queue->isEmpty()) {
119 // If there are no transfers, then sleep for the next delay
120 if (!$this->active && $this->delays) {
121 usleep($this->timeToNext());
127 private function addRequest(array $entry)
129 $easy = $entry['easy'];
130 $id = (int) $easy->handle;
131 $this->handles[$id] = $entry;
132 if (empty($easy->options['delay'])) {
133 curl_multi_add_handle($this->_mh, $easy->handle);
135 $this->delays[$id] = microtime(true) + ($easy->options['delay'] / 1000);
140 * Cancels a handle from sending and removes references to it.
142 * @param int $id Handle ID to cancel and remove.
144 * @return bool True on success, false on failure.
146 private function cancel($id)
148 // Cannot cancel if it has been processed.
149 if (!isset($this->handles[$id])) {
153 $handle = $this->handles[$id]['easy']->handle;
154 unset($this->delays[$id], $this->handles[$id]);
155 curl_multi_remove_handle($this->_mh, $handle);
161 private function processMessages()
163 while ($done = curl_multi_info_read($this->_mh)) {
164 $id = (int) $done['handle'];
165 curl_multi_remove_handle($this->_mh, $done['handle']);
167 if (!isset($this->handles[$id])) {
168 // Probably was cancelled.
172 $entry = $this->handles[$id];
173 unset($this->handles[$id], $this->delays[$id]);
174 $entry['easy']->errno = $done['result'];
175 $entry['deferred']->resolve(
185 private function timeToNext()
187 $currentTime = microtime(true);
188 $nextTime = PHP_INT_MAX;
189 foreach ($this->delays as $time) {
190 if ($time < $nextTime) {
195 return max(0, $nextTime - $currentTime) * 1000000;