-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimpleMultiCURL.php
124 lines (98 loc) · 3.24 KB
/
SimpleMultiCURL.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
<?php
class SimpleMultiCURL
{
/**
* @var SimpleCURL[] $simpleCURLS
*/
private array $simpleCURLS;
private array $curlChs;
private array $curlsData;
private int $batchThread;
private $mch;
private $exception = true;
private $errors;
public function __construct($batchThread = 50, $exception = true)
{
$this->batchThread = $batchThread;
$this->mch = curl_multi_init();
$this->exception = $exception;
}
/**
* @param SimpleCURL $simpleCURL
* @param $data
* @return $this
* @throws Exception
*/
public function add(SimpleCURL $simpleCURL, $data = null): self
{
try {
$this->simpleCURLS[] = $simpleCURL;
$this->curlChs[] = $simpleCURL->getCurlResource();
$this->curlsData[] = $data ?: $simpleCURL->getData();
}catch (Exception $exception){
throw new Exception($exception->getMessage());
}
return $this;
}
/**
* @return array
* @throws Exception
*/
public function send(): array
{
$active = null;
do {
if(0 < count($this->curlChs) && $active <= $this->batchThread) {
if ($errno = curl_multi_add_handle($this->mch, array_shift($this->curlChs))) {
throw new Exception(curl_multi_strerror($errno));
}
}
$mexec = curl_multi_exec($this->mch, $active);
usleep(1000);
} while ($mexec == CURLM_OK && $active > 0);
/* Curl error handling */
while ($result = curl_multi_info_read($this->mch)) {
if ($errno = $result['result']) {
if($this->exception) {
throw new Exception(curl_strerror($errno));
}else{
foreach ($this->simpleCURLS as $key => $simpleCURL){
if($simpleCURL->getCurlResource() === $result['handle']){
$this->errors[$key] = curl_strerror($errno);
}
}
}
}
}
/* Curl response */
foreach ($this->simpleCURLS as $key => $simpleCURL){
$ch = $simpleCURL->getCurlResource();
$info = curl_getinfo($ch);
$response = curl_multi_getcontent($ch);
$simpleCURL->multCurlResponsCreater(
$response,
substr($response, 0, $info['header_size']),
substr($response, $info['header_size']),
$info,
$this->curlsData[$key],
$this->errors[$key] ?? ''
);
curl_multi_remove_handle($this->mch, $ch);
curl_close($ch);
}
if($errno = curl_multi_errno($this->mch)){
throw new Exception(curl_multi_strerror($errno));
}
curl_multi_close($this->mch);
return $this->simpleCURLS;
}
/**
* @return void
*/
public function flush()
{
$this->simpleCURLS = [];
$this->curlChs = [];
$this->curlsData = [];
}
}