Completed
Push — master ( d30d8a...80cd4c )
by Dan
02:22
created

Guzzle::scheduleProcessing()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.2
c 0
b 0
f 0
cc 4
eloc 9
nc 2
nop 0
1
<?php
2
namespace Nopolabs\Yabot\Guzzle;
3
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\Handler\CurlMultiHandler;
7
use GuzzleHttp\Promise\PromiseInterface;
8
use function GuzzleHttp\Promise\queue;
9
use Psr\Http\Message\ResponseInterface;
10
use React\EventLoop\LoopInterface;
11
use React\EventLoop\Timer\TimerInterface;
12
13
class Guzzle
14
{
15
    /** @var Client */
16
    private $client;
17
18
    /** @var LoopInterface */
19
    private $eventloop;
20
21
    /** @var CurlMultiHandler */
22
    private $handler;
23
24
    /** @var TimerInterface */
25
    public $timer;
26
27
    public function __construct(Client $client, CurlMultiHandler $handler, LoopInterface $eventLoop)
28
    {
29
        $this->client = $client;
30
        $this->handler = $handler;
31
        $this->eventloop = $eventLoop;
32
    }
33
34
    public function getClient() : Client
35
    {
36
        return $this->client;
37
    }
38
39
    public function getAsync(string $uri, array $options = []) : PromiseInterface
40
    {
41
        $request = $this->client->getAsync($uri, $options);
42
43
        $this->scheduleProcessing();
44
45
        return $request;
46
    }
47
48
    public function post(string $uri, array $options = []) : ResponseInterface
49
    {
50
        return $this->client->post($uri, $options);
51
    }
52
53
    /**
54
     * @see http://stephencoakley.com/2015/06/11/integrating-guzzle-6-asynchronous-requests-with-reactphp
55
     *
56
     * Jiggerery with Closure::bind to get access to CurlMultiHandler::handles private member.
57
     */
58
    private function scheduleProcessing()
59
    {
60
        if ($this->timer === null) {
61
            $self = & $this;
62
            $this->timer = $this->eventloop->addPeriodicTimer(0, \Closure::bind(function() use (&$self) {
63
64
                $this->tick();
65
66
                // Stop the timer when there are no more requests
67
                if (empty($this->handles) && queue()->isEmpty()) {
68
                    $self->timer->cancel();
69
                    $self->timer = null;
70
                }
71
            }, $this->handler, $this->handler));
72
        }
73
    }
74
}