forked from jae-jae/QueryList-CurlMulti
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CurlMulti.php
118 lines (100 loc) · 2.77 KB
/
CurlMulti.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
<?php
/**
* Created by PhpStorm.
* User: Jaeger <[email protected]>
* Date: 2017/9/27
* Curl multi threading
*/
namespace QL\Ext;
use Ares333\Curl\Curl;
use QL\Contracts\PluginContract;
use QL\QueryList;
use Closure;
class CurlMulti implements PluginContract
{
protected $urls = [];
protected $queryList;
protected $successCallback;
protected $curl;
protected $isRunning = false;
public function __construct(QueryList $queryList,$urls)
{
$this->urls = is_string($urls)?[$urls]:$urls;
$this->queryList = $queryList;
$this->curl = new Curl();
$this->curl->opt = [
CURLOPT_RETURNTRANSFER => true
];
}
public static function install(QueryList $queryList, ...$opt)
{
$name = $opt[0] ?? 'curlMulti';
$queryList->bind($name,function ($urls = []){
return new CurlMulti($this,$urls);
});
}
public function getUrls()
{
return $this->urls;
}
public function add($urls)
{
is_string($urls) && $urls = [$urls];
$this->urls = array_merge($this->urls,$urls);
//如果当前任务正在运行就实时动态添加任务
$this->isRunning && $this->addTasks($urls);
return $this;
}
public function success(Closure $callback)
{
$this->successCallback = function ($r) use($callback){
$this->queryList->setHtml($r['body']);
$callback($this->queryList,$this,$r);
};
return $this;
}
public function error(Closure $callback)
{
$this->curl->cbFail = function ($info) use($callback){
$callback($info,$this);
};
return $this;
}
public function start(array $opt = [])
{
$this->bindOpt($opt);
$this->addTasks($this->urls);
$this->isRunning = true;
$this->curl->start();
$this->isRunning = false;
$this->urls = [];
return $this;
}
protected function bindOpt($opt)
{
foreach ($opt as $key => $value) {
if($key == 'opt'){
$this->curl->opt = $this->arrayMerge($this->curl->opt,$value);
}else {
$this->curl->$key = $value;
}
}
}
protected function addTasks($urls)
{
foreach ($urls as $url) {
$this->curl->add([
'opt' => array(
CURLOPT_URL => $url
)
],$this->successCallback);
}
}
protected function arrayMerge($arr1,$arr2)
{
foreach ($arr2 as $key => $value) {
$arr1[$key] = $value;
}
return $arr1;
}
}