Completed
Pull Request — master (#2)
by
unknown
02:18
created

Dispatcher::getDriver()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace Dazzle\Redis;
4
5
use Dazzle\Socket\Socket;
6
use Dazzle\Promise\Deferred;
7
use Dazzle\Loop\LoopInterface;
8
use Dazzle\Redis\Driver\Driver;
9
use Dazzle\Socket\SocketInterface;
10
use Dazzle\Event\AsyncEventEmitter;
11
use Dazzle\Redis\Driver\DriverInterface;
12
use Dazzle\Throwable\Exception\Runtime\ExecutionException;
13
use Dazzle\Throwable\Exception\Runtime\UnderflowException;
14
use Error;
15
use Exception;
16
17
use Clue\Redis\Protocol\Model\ErrorReply;
18
use Clue\Redis\Protocol\Model\ModelInterface;
19
use Clue\Redis\Protocol\Parser\ParserException;
20
21
class Dispatcher extends AsyncEventEmitter
22
{
23
    /**
24
     * Stream
25
     * @var SocketInterface
26
     */
27
    private $stream;
28
29
    /**
30
     * Deferred requests
31
     * @var array
32
     */
33
    private $reqs;
34
35
    /**
36
     * Driver of RESP protocol
37
     * @var DriverInterface
38
     */
39
    private $protocol;
40
41
    /**
42
     * Flag of ending
43
     * @var bool
44
     */
45
    private $ending;
46
47
    /**
48
     * Flag of closed
49
     * @var bool
50
     */
51
    private $closed;
52
53
    /**
54
     * Constructor
55
     * @param LoopInterface $loop
56
     */
57
    public function __construct(LoopInterface $loop)
58
    {
59
        parent::__construct($loop);
60
        $this->reqs = [];
61
        $this->ending = false;
62
        $this->closed = false;
63
        $this->protocol = new Driver();
64
        $this->on('connect', [$this, 'handleConnect']);
65
        $this->on('response',[$this, 'handleResponse']);
66
        $this->on('disconnect',[$this, 'handleDisconnect']);
67
        $this->on('close', [$this, 'handleClose']);
68
    }
69
70
    /**
71
     * Destructor
72
     */
73
    public function __destruct()
74
    {
75
        if ($this->ending != true)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison !== instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
76
        {
77
            $this->handleDisconnect();        
78
        }
79
        else 
80
        {
81
            $this->handleClose();        
82
        }
83
    }
84
85
     /**
86
     * Create socket client with connection to Redis database.
87
     *
88
     * @param string $endpoint
89
     * @return SocketInterface
90
     * @throws ExecutionException
91
     */
92
    protected function createClient($endpoint)
93
    {
94
        $ex = null;
95
96
        try
97
        {
98
            return new Socket($endpoint, $this->loop);
0 ignored issues
show
Bug introduced by
It seems like $this->loop can be null; however, __construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
99
        }
100
        catch (Error $ex)
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
101
        {}
102
        catch (Exception $ex)
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
103
        {}
104
105
        throw new ExecutionException('Redis connection socket could not be created!', 0, $ex);
106
    }
107
108
    /**
109
     * Get RESP Driver
110
     * @return DriverInterface
111
     */
112
    public function getDriver()
113
    {
114
        return $this->protocol;
115
    }
116
117
    /**
118
     * Get dispatcher ending flag
119
     * @return bool
120
     */
121
    public function isEnding()
122
    {
123
        return $this->ending? true: false;
124
    }
125
126
    /**
127
     * Append request
128
     * @param $req
129
     */
130
    public function appendRequest($req)
131
    {
132
        $this->reqs[] = $req;
133
    }
134
135
    /**
136
     * Watch and dispatch streaming
137
     * @param $endpoint
138
     */
139
    public function watch($endpoint)
140
    {
141
        if ($this->stream !== null) {
142
            return;
143
        }
144
145
        try {
146
            $this->stream = $this->createClient($endpoint);
147
        } catch (\Exception $e) {
148
            $this->emit('error', [$e]);
149
        }
150
151
        if ($this->stream->isOpen()) {
152
            $this->emit('connect', [$this]);
153
        }
154
155
    }
156
157
    /**
158
     * @internal
159
     */
160
    public function handleConnect()
161
    {
162
        $this->stream->on('data', [$this, 'handleData']);
163
        $this->emit('request');
164
    }
165
166
    /**
167
     * @internal
168
     * @param $_
169
     * @param $data
170
     */
171
    public function handleData($_, $data)
172
    {
173
        try {
174
            $models = $this->protocol->parseResponse($data);
175
        } catch (ParserException $error) {
176
            $this->emit('error', [$error]);
177
178
            return;
179
        }
180
181
        foreach ($models as $data) {
182
            try {
183
                $this->emit('response', [$data]);
184
            } catch (UnderflowException $error) {
185
                $this->emit('error', [$error]);
186
187
                break;
188
            }
189
        }
190
    }
191
192
    /**
193
     * @internal
194
     * @param $payload
195
     */
196
    public function handleRequest($payload)
197
    {
198
        $this->stream->write($payload);
199
    }
200
201
    /**
202
     * @internal
203
     */
204
    public function handleResponse(ModelInterface $message)
205
    {
206
        if (!$this->reqs) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->reqs of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
207
            throw new UnderflowException('Unexpected reply received, no matching request found');
208
        }
209
        /* @var Deferred $req */
210
        $req = array_shift($this->reqs);
211
212
        if ($message instanceof ErrorReply) {
213
            $req->reject($message);
214
        } else {
215
            $req->resolve($message->getValueNative());
216
        }
217
218
        if (count($this->reqs) <= 0) {
219
            $this->emit('disconnect');
220
        }
221
    }
222
223
    /**
224
     * @internal
225
     */
226
    public function handleDisconnect()
227
    {
228
        $this->ending = true;
229
        // reject all remaining requests in the queue
230
        while($this->reqs) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->reqs of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
231
            $req = array_shift($this->reqs);
232
            /* @var $req Deferred */
233
            $req->reject(new RuntimeException('Connection closing'));
234
        }
235
        $this->stream->close();
236
        $this->emit('close');
237
    }
238
239
    /**
240
     * @internal
241
     */
242
    public function handleClose()
243
    {
244
        if ($this->closed) {
245
            return;
246
        }
247
        $this->removeListeners('connect');
248
        $this->removeListeners('response');
249
        $this->removeListeners('disconnect');
250
        $this->removeListeners('close');
251
        $this->removeListeners('error');
252
        $this->closed = true;
253
    }
254
}