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

Guzzle   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 8
c 3
b 0
f 0
lcom 1
cbo 4
dl 0
loc 62
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A getClient() 0 4 1
A getAsync() 0 8 1
A post() 0 4 1
A scheduleProcessing() 0 16 4
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
}