Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
queue.php
1<?php
2
11
14
15class Queue extends Http\Queue
16{
18 protected array $promises = [];
19 protected \CurlMultiHandle $handle;
20
21 public function __construct(bool $backgroundJob = true)
22 {
23 parent::__construct($backgroundJob);
24
25 $this->handle = curl_multi_init();
26 }
27
28 public function __destruct()
29 {
30 curl_multi_close($this->handle);
31 }
32
39 public function add(Promise $promise): void
40 {
41 $this->promises[$promise->getId()] = $promise;
42
43 curl_multi_add_handle($this->handle, $promise->getHandler()->getHandle());
44 }
45
46 protected function delete(string $promiseId): void
47 {
48 curl_multi_remove_handle($this->handle, $this->promises[$promiseId]->getHandler()->getHandle());
49
50 unset($this->promises[$promiseId]);
51 }
52
56 public function wait(?Http\Promise $targetPromise = null): array
57 {
58 $processedPromises = [];
59
60 if (empty($this->promises))
61 {
62 return $processedPromises;
63 }
64
65 do
66 {
67 $fetchBody = true;
68
69 try
70 {
71 $status = curl_multi_exec($this->handle, $active);
72 }
73 catch (SkipBodyException $e)
74 {
75 $fetchBody = false;
76 }
77
78 $info = curl_multi_info_read($this->handle);
79
80 if ($info !== false)
81 {
82 $promiseId = spl_object_hash($info['handle']);
83
84 $promise = $this->promises[$promiseId];
85 $handler = $promise->getHandler();
86
87 if (!$fetchBody)
88 {
89 // we don't want a body, just fulfil a promise with response headers
90 $promise->fulfill($handler->getResponse());
91 }
92 elseif ($info['result'] === CURLE_OK)
93 {
94 $response = $handler->getResponse();
95
96 if ($handler->getDebugLevel() & HttpDebug::RESPONSE_BODY)
97 {
98 $handler->log($response->getBody(), HttpDebug::RESPONSE_BODY);
99 }
100
101 // need to ajust the response headers (PSR-18)
102 $response->adjustHeaders();
103
104 $promise->fulfill($response);
105 }
106 else
107 {
108 $error = curl_error($info['handle']);
109
110 $promise->reject(new Http\NetworkException($promise->getRequest(), $error));
111
112 if ($logger = $handler->getLogger())
113 {
114 $logger->error($error);
115 }
116 }
117
118 // job done, the promise is fullfilled or rejected
119 $processedPromises[] = $promise;
120
121 $this->delete($promiseId);
122
123 if ($targetPromise && $promiseId === $targetPromise->getId())
124 {
125 // we were waiting for the specific promise
126 return $processedPromises;
127 }
128 }
129 }
130 while ($status === CURLM_CALL_MULTI_PERFORM || $active);
131
132 return $processedPromises;
133 }
134}
add(Promise $promise)
Definition queue.php:39
__construct(bool $backgroundJob=true)
Definition queue.php:21
wait(?Http\Promise $targetPromise=null)
Definition queue.php:56
CurlMultiHandle $handle
Definition queue.php:19