1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Nopolabs\Yabot\Guzzle; |
4
|
|
|
|
5
|
|
|
|
6
|
|
|
use GuzzleHttp\Handler\CurlFactory; |
7
|
|
|
use GuzzleHttp\Handler\CurlFactoryInterface; |
8
|
|
|
use GuzzleHttp\Handler\CurlMultiHandler; |
9
|
|
|
use GuzzleHttp\Handler\EasyHandle; |
10
|
|
|
use Psr\Http\Message\RequestInterface; |
11
|
|
|
use Psr\Log\LoggerInterface; |
12
|
|
|
use Psr\Log\NullLogger; |
13
|
|
|
use React\EventLoop\LoopInterface; |
14
|
|
|
use React\EventLoop\Timer\TimerInterface; |
15
|
|
|
|
16
|
|
|
class ReactAwareCurlFactory implements CurlFactoryInterface |
17
|
|
|
{ |
18
|
|
|
private $eventLoop; |
19
|
|
|
private $logger; |
20
|
|
|
private $factory; |
21
|
|
|
private $count; |
22
|
|
|
|
23
|
|
|
/** @var CurlMultiHandler */ |
24
|
|
|
private $handler; |
25
|
|
|
|
26
|
|
|
/** @var TimerInterface */ |
27
|
|
|
private $timer; |
28
|
|
|
|
29
|
|
|
public function __construct(LoopInterface $eventLoop, LoggerInterface $logger = null) |
30
|
|
|
{ |
31
|
|
|
$this->eventLoop = $eventLoop; |
32
|
|
|
$this->logger = $logger ?? new NullLogger(); |
33
|
|
|
|
34
|
|
|
$this->factory = new CurlFactory(50); |
35
|
|
|
$this->count = 0; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function setHandler(CurlMultiHandler $handler) |
39
|
|
|
{ |
40
|
|
|
$this->handler = $handler; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
public function tick() |
44
|
|
|
{ |
45
|
|
|
$this->handler->tick(); |
46
|
|
|
|
47
|
|
|
if ($this->count === 0 && \GuzzleHttp\Promise\queue()->isEmpty()) { |
48
|
|
|
$this->stopTimer(); |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
public function create(RequestInterface $request, array $options) |
53
|
|
|
{ |
54
|
|
|
$this->incrementCount(); |
55
|
|
|
|
56
|
|
|
return $this->factory->create($request, $options); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function release(EasyHandle $easy) |
60
|
|
|
{ |
61
|
|
|
$this->factory->release($easy); |
62
|
|
|
|
63
|
|
|
$this->decrementCount(); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
private function incrementCount() |
67
|
|
|
{ |
68
|
|
|
if ($this->count === 0) { |
69
|
|
|
$this->startTimer(); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
$this->count++; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
private function decrementCount() |
76
|
|
|
{ |
77
|
|
|
$this->count--; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
private function startTimer() |
81
|
|
|
{ |
82
|
|
|
if ($this->timer === null) { |
83
|
|
|
$this->timer = $this->eventLoop->addPeriodicTimer(0, [$this, 'tick']); |
84
|
|
|
|
85
|
|
|
$this->logger->debug('ReactAwareCurlFactory started periodic queue processing'); |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
private function stopTimer() |
90
|
|
|
{ |
91
|
|
|
if ($this->timer !== null) { |
92
|
|
|
$this->timer->cancel(); |
93
|
|
|
$this->timer = null; |
94
|
|
|
|
95
|
|
|
$this->logger->debug('ReactAwareCurlFactory stopped periodic queue processing'); |
96
|
|
|
} |
97
|
|
|
} |
98
|
|
|
} |