Completed
Push — master ( 0c3a5b...29b964 )
by Taosikai
11:38
created

Client::reset()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 4
nop 0
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the slince/spike package.
5
 *
6
 * (c) Slince <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Spike\Client;
13
14
use Doctrine\Common\Collections\ArrayCollection;
15
use Doctrine\Common\Collections\Collection;
16
use React\EventLoop\Factory;
17
use React\EventLoop\LoopInterface;
18
use React\Socket\ConnectionInterface;
19
use React\Socket\Connector;
20
use function Slince\Common\jsonBuffer;
21
use Slince\Event\Dispatcher;
22
use Slince\Event\DispatcherInterface;
23
use Slince\Event\Event;
24
use Spike\Client\Event\Events;
25
use Spike\Client\Event\FilterActionHandlerEvent;
26
use Spike\Client\Listener\ClientListener;
27
use Spike\Client\Listener\LoggerListener;
28
use Spike\Client\Worker\WorkerInterface;
29
use Spike\Common\Logger\Logger;
30
use Spike\Common\Protocol\Spike;
31
use Spike\Common\Timer\TimersAware;
32
use Spike\Version;
33
use Symfony\Component\Console\Application;
34
use Symfony\Component\Console\Input\InputInterface;
35
use Symfony\Component\Console\Output\OutputInterface;
36
37
class Client extends Application implements ClientInterface
38
{
39
    use TimersAware;
40
41
    /**
42
     * @var string
43
     */
44
    const LOGO = <<<EOT
45
 _____   _____   _   _   _    _____  
46
/  ___/ |  _  \ | | | | / /  | ____| 
47
| |___  | |_| | | | | |/ /   | |__   
48
\___  \ |  ___/ | | | |\ \   |  __|  
49
 ___| | | |     | | | | \ \  | |___  
50
/_____/ |_|     |_| |_|  \_\ |_____| 
51
52
53
EOT;
54
55
    /**
56
     * @var string
57
     */
58
    const NAME = 'Spike Client';
59
60
    /**
61
     * @var string
62
     */
63
    protected $id;
64
65
    /**
66
     * @var Configuration
67
     */
68
    protected $configuration;
69
70
    /**
71
     * @var LoopInterface
72
     */
73
    protected $eventLoop;
74
75
    /**
76
     * @var DispatcherInterface
77
     */
78
    protected $eventDispatcher;
79
80
    /**
81
     * @var ConnectionInterface
82
     */
83
    protected $controlConnection;
84
85
    /**
86
     * @var \DateTimeInterface
87
     */
88
    protected $activeAt;
89
90
    /**
91
     * @var WorkerInterface[]|Collection
92
     */
93
    protected $workers;
94
95
    /**
96
     * @var Logger
97
     */
98
    protected $logger;
99
100
    /**
101
     * @var bool
102
     */
103
    protected $running = false;
104
105
    /**
106
     * Whether connect to server.
107
     * @var bool
108
     */
109
    protected $connected = false;
110
111
    public function __construct(Configuration $configuration, LoopInterface $eventLoop = null)
112
    {
113
        $this->configuration = $configuration;
114
        $this->eventLoop = $eventLoop ?: Factory::create();
115
        $this->eventDispatcher = new Dispatcher();
116
        $this->workers = new ArrayCollection();
117
        $this->initializeEvents();
118
        parent::__construct(static::NAME, Version::VERSION);
119
    }
120
121
    /**
122
     * {@inheritdoc}
123
     */
124
    public function getHelp()
125
    {
126
        return static::LOGO.parent::getHelp();
127
    }
128
129
    /**
130
     * {@inheritdoc}
131
     *
132
     * @codeCoverageIgnore
133
     */
134
    public function doRun(InputInterface $input, OutputInterface $output)
135
    {
136
        $this->logger = new Logger(
137
            $this->eventLoop,
138
            $this->getConfiguration()->getLogLevel(),
139
            $this->getConfiguration()->getLogFile(),
140
            $output
141
        );
142
        // Execute command if the command name is exists
143
        if ($this->getCommandName($input) ||
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->getCommandName($input) of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
144
            true === $input->hasParameterOption(array('--help', '-h'), true)
145
        ) {
146
            $exitCode = parent::doRun($input, $output);
147
        } else {
148
            $exitCode = $this->start();
149
        }
150
151
        return $exitCode;
152
    }
153
154
    /**
155
     * {@inheritdoc}
156
     */
157
    public function start()
158
    {
159
        $connector = new Connector($this->eventLoop, [
160
            'timeout' => $this->configuration->get('timeout', 5)
161
        ]);
162
        $connector->connect($this->configuration->getServerAddress())->then(function($connection){
163
            $this->connected = true; //Set connect status
164
            $this->initializeTimers();
165
            $this->handleControlConnection($connection);
166
        }, function(){
167
            $this->eventDispatcher->dispatch(new Event(Events::CANNOT_CONNECT_SERVER, $this));
168
        });
169
        $this->running = true; //Set running status
170
        $this->eventDispatcher->dispatch(Events::CLIENT_RUN);
171
        $this->eventLoop->run();
172
173
        return 0;
174
    }
175
176
    /**
177
     * {@inheritdoc}
178
     */
179
    public function close()
180
    {
181
        if (!$this->running) {
182
            return;
183
        }
184
        //Reset the client
185
        $this->reset();
186
        if ($this->controlConnection) {
187
            //don't trigger "close" event if closed by client
188
            $this->controlConnection->removeListener('close', [$this, 'handleDisconnectServer']);
189
            $this->controlConnection->end();
190
        }
191
        $this->running = false;
192
    }
193
194
195
    protected function reset()
196
    {
197
        $this->connected = false;
198
        foreach ($this->getTimers() as $timer) {
199
            $this->cancelTimer($timer);
200
        }
201
        $this->timers = [];
202
        foreach ($this->workers as $worker) {
203
            $worker->close();
204
        }
205
        $this->workers = new ArrayCollection();
206
    }
207
208
    /**
209
     * Reconnect if disconnect from server.
210
     */
211
    public function handleDisconnectServer()
212
    {
213
        $this->eventDispatcher->dispatch(new Event(Events::DISCONNECT_FROM_SERVER, $this));
214
        $this->close();
215
    }
216
217
    /**
218
     * Handles the control connection.
219
     *
220
     * @param ConnectionInterface $connection
221
     * @codeCoverageIgnore
222
     */
223
    protected function handleControlConnection(ConnectionInterface $connection)
224
    {
225
        $this->controlConnection = $connection;
226
        //Emit the event
227
        $this->eventDispatcher->dispatch(new Event(Events::CLIENT_CONNECT, $this, [
228
            'connection' => $connection,
229
        ]));
230
        //Sends auth request
231
        $this->sendAuthRequest($connection);
232
        //Distinct from server
233
        $connection->on('close', [$this, 'handleDisconnectServer']);
234
235
        jsonBuffer($connection, function($messages) use ($connection){
236
            foreach ($messages as $messageData) {
237
                if (!$messageData) {
238
                    continue;
239
                }
240
                $message = Spike::fromArray($messageData);
241
242
                //Fires filter action handler event
243
                $event = new FilterActionHandlerEvent($this, $message, $connection);
244
                $this->eventDispatcher->dispatch($event);
245
246
                if ($actionHandler = $event->getActionHandler()) {
247
                    $actionHandler->handle($message);
248
                }
249
            }
250
        }, function($exception) use ($connection){
251
            $this->eventDispatcher->dispatch(new Event(Events::CONNECTION_ERROR, $this, [
252
                'connection' => $connection,
253
                'exception' => $exception,
254
            ]));
255
        });
256
    }
257
258
    /**
259
     * Request for auth.
260
     *
261
     * @param ConnectionInterface $connection
262
     * @codeCoverageIgnore
263
     */
264
    protected function sendAuthRequest(ConnectionInterface $connection)
265
    {
266
        $authInfo = array_replace([
267
            'os' => PHP_OS,
268
            'version' => Version::VERSION,
269
        ], $this->configuration->get('auth', []));
270
271
        $connection->write(new Spike('auth', $authInfo));
272
    }
273
274
    /**
275
     * @return Configuration
276
     */
277
    public function getConfiguration()
278
    {
279
        return $this->configuration;
280
    }
281
282
    /**
283
     * {@inheritdoc}
284
     */
285
    public function getControlConnection()
286
    {
287
        return $this->controlConnection;
288
    }
289
290
    /**
291
     * {@inheritdoc}
292
     */
293
    public function getId()
294
    {
295
        return $this->id;
296
    }
297
298
    /**
299
     * {@inheritdoc}
300
     */
301
    public function setId($id)
302
    {
303
        $this->id = $id;
304
    }
305
306
    /**
307
     * {@inheritdoc}
308
     */
309
    public function getActiveAt()
310
    {
311
        return $this->activeAt;
312
    }
313
314
    /**
315
     * {@inheritdoc}
316
     */
317
    public function getEventDispatcher()
318
    {
319
        return $this->eventDispatcher;
320
    }
321
322
    /**
323
     * @param \DateTimeInterface $activeAt
324
     */
325
    public function setActiveAt($activeAt)
326
    {
327
        $this->activeAt = $activeAt;
328
    }
329
330
    /**
331
     * @return LoopInterface
332
     */
333
    public function getEventLoop()
334
    {
335
        return $this->eventLoop;
336
    }
337
338
    /**
339
     * @return Collection|WorkerInterface[]
340
     */
341
    public function getWorkers()
342
    {
343
        return $this->workers;
344
    }
345
346
    /**
347
     * @return Logger
348
     */
349
    public function getLogger()
350
    {
351
        return $this->logger;
352
    }
353
354
    /**
355
     * {@inheritdoc}
356
     */
357
    protected function getDefaultCommands()
358
    {
359
        return array_merge(parent::getDefaultCommands(), [
0 ignored issues
show
Best Practice introduced by
The expression return array_merge(paren...d\InitCommand($this))); seems to be an array, but some of its elements' types (Spike\Client\Command\Sho...ent\Command\InitCommand) are incompatible with the return type of the parent method Symfony\Component\Consol...ion::getDefaultCommands of type array<Symfony\Component\...le\Command\ListCommand>.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
360
            new Command\ShowProxyHostsCommand($this),
361
            new Command\InitCommand($this),
362
        ]);
363
    }
364
365
    protected function initializeEvents()
366
    {
367
        $this->eventDispatcher->addSubscriber(new ClientListener());
368
        $this->eventDispatcher->addSubscriber(new LoggerListener($this));
369
    }
370
371
    /**
372
     * Creates default timers.
373
     *
374
     * @codeCoverageIgnore
375
     */
376
    protected function initializeTimers()
377
    {
378
        $this->addTimer(new Timer\Heartbeat($this));
379
    }
380
}