Client::sendAuthRequest()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 9
rs 9.9666
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\EventDispatcher\Dispatcher;
22
use Slince\EventDispatcher\DispatcherInterface;
23
use Slince\EventDispatcher\Event;
24
use Spike\Client\Event\Events;
25
use Spike\Client\Event\FilterActionHandlerEvent;
26
use Spike\Client\Worker\WorkerInterface;
27
use Spike\Common\Logger\Logger;
28
use Spike\Common\Protocol\Spike;
29
use Spike\Common\Timer\MemoryWatchTimer;
30
use Spike\Common\Timer\TimersAware;
31
use Spike\Version;
32
use Symfony\Component\Console\Application;
33
use Symfony\Component\Console\Input\InputInterface;
34
use Symfony\Component\Console\Output\OutputInterface;
35
36
class Client extends Application implements ClientInterface
37
{
38
    use TimersAware;
39
40
    /**
41
     * @var string
42
     */
43
    const LOGO = <<<EOT
44
 _____   _____   _   _   _    _____  
45
/  ___/ |  _  \ | | | | / /  | ____| 
46
| |___  | |_| | | | | |/ /   | |__   
47
\___  \ |  ___/ | | | |\ \   |  __|  
48
 ___| | | |     | | | | \ \  | |___  
49
/_____/ |_|     |_| |_|  \_\ |_____| 
50
51
52
EOT;
53
54
    /**
55
     * @var string
56
     */
57
    const NAME = 'Spike Client';
58
59
    /**
60
     * @var string
61
     */
62
    protected $id;
63
64
    /**
65
     * @var Configuration
66
     */
67
    protected $configuration;
68
69
    /**
70
     * @var LoopInterface
71
     */
72
    protected $eventLoop;
73
74
    /**
75
     * @var DispatcherInterface
76
     */
77
    protected $eventDispatcher;
78
79
    /**
80
     * @var ConnectionInterface
81
     */
82
    protected $controlConnection;
83
84
    /**
85
     * @var \DateTimeInterface
86
     */
87
    protected $activeAt;
88
89
    /**
90
     * @var WorkerInterface[]|Collection
91
     */
92
    protected $workers;
93
94
    /**
95
     * @var Logger
96
     */
97
    protected $logger;
98
99
    /**
100
     * @var bool
101
     */
102
    protected $running = false;
103
104
    /**
105
     * Whether connect to server.
106
     * @var bool
107
     */
108
    protected $connected = false;
109
110
    public function __construct(Configuration $configuration, LoopInterface $eventLoop = null)
111
    {
112
        $this->configuration = $configuration;
113
        $this->eventLoop = $eventLoop ?: Factory::create();
114
        $this->eventDispatcher = new Dispatcher();
115
        $this->workers = new ArrayCollection();
116
        $this->initializeEvents();
117
        parent::__construct(static::NAME, Version::VERSION);
118
    }
119
120
    /**
121
     * {@inheritdoc}
122
     */
123
    public function getHelp()
124
    {
125
        return static::LOGO.parent::getHelp();
126
    }
127
128
    /**
129
     * {@inheritdoc}
130
     *
131
     * @codeCoverageIgnore
132
     */
133
    public function doRun(InputInterface $input, OutputInterface $output)
134
    {
135
        $this->logger = new Logger(
136
            $this->eventLoop,
137
            $this->getConfiguration()->getLogLevel(),
138
            $this->getConfiguration()->getLogFile(),
139
            $output
140
        );
141
        // Execute command if the command name is exists
142
        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...
143
            true === $input->hasParameterOption(array('--help', '-h'), true)
144
        ) {
145
            $exitCode = parent::doRun($input, $output);
146
        } else {
147
            $exitCode = $this->start();
148
        }
149
150
        return $exitCode;
151
    }
152
153
    /**
154
     * {@inheritdoc}
155
     */
156
    public function start()
157
    {
158
        $connector = new Connector($this->eventLoop, [
159
            'timeout' => $this->configuration->get('timeout', 5)
160
        ]);
161
        $connector->connect($this->configuration->getServerAddress())->then(function($connection){
162
            $this->connected = true; //Set connect status
163
            $this->initializeTimers();
164
            $this->handleControlConnection($connection);
165
        }, function(){
166
            $this->eventDispatcher->dispatch(new Event(Events::CANNOT_CONNECT_SERVER, $this));
167
        });
168
        $this->running = true; //Set running status
169
        $this->eventDispatcher->dispatch(Events::CLIENT_RUN);
170
        $this->eventLoop->run();
171
172
        return 0;
173
    }
174
175
    /**
176
     * {@inheritdoc}
177
     */
178
    public function close()
179
    {
180
        if (!$this->running) {
181
            return;
182
        }
183
        //Reset the client
184
        $this->reset();
185
        if ($this->controlConnection) {
186
            //don't trigger "close" event if closed by client
187
            $this->controlConnection->removeListener('close', [$this, 'handleDisconnectServer']);
188
            $this->controlConnection->end();
189
        }
190
        $this->running = false;
191
    }
192
193
194
    protected function reset()
195
    {
196
        $this->connected = false;
197
        foreach ($this->getTimers() as $timer) {
198
            $this->cancelTimer($timer);
199
        }
200
        $this->timers = [];
201
        foreach ($this->workers as $worker) {
202
            $worker->stop();
203
        }
204
        $this->workers = new ArrayCollection();
205
    }
206
207
    /**
208
     * Reconnect if disconnect from server.
209
     */
210
    public function handleDisconnectServer()
211
    {
212
        $this->eventDispatcher->dispatch(new Event(Events::DISCONNECT_FROM_SERVER, $this));
213
        $this->close();
214
    }
215
216
    /**
217
     * Handles the control connection.
218
     *
219
     * @param ConnectionInterface $connection
220
     * @codeCoverageIgnore
221
     */
222
    protected function handleControlConnection(ConnectionInterface $connection)
223
    {
224
        $this->controlConnection = $connection;
225
        //Emit the event
226
        $this->eventDispatcher->dispatch(new Event(Events::CLIENT_CONNECT, $this, [
227
            'connection' => $connection,
228
        ]));
229
        //Sends auth request
230
        $this->sendAuthRequest($connection);
231
        //Disconnect from server
232
        $connection->on('close', [$this, 'handleDisconnectServer']);
233
234
        jsonBuffer($connection, function($messages) use ($connection){
235
            foreach ($messages as $messageData) {
236
                if (!$messageData) {
237
                    continue;
238
                }
239
                $message = Spike::fromArray($messageData);
240
241
                //Fires filter action handler event
242
                $event = new FilterActionHandlerEvent($this, $message, $connection);
243
                $this->eventDispatcher->dispatch($event);
244
245
                if ($actionHandler = $event->getActionHandler()) {
246
                    try {
247
                        $actionHandler->handle($message);
248
                    } catch (\Exception $exception) {
249
                        //ignore bad message
250
                    }
251
                }
252
            }
253
        }, function($exception) use ($connection){
254
            $this->eventDispatcher->dispatch(new Event(Events::CONNECTION_ERROR, $this, [
255
                'connection' => $connection,
256
                'exception' => $exception,
257
            ]));
258
        });
259
    }
260
261
    /**
262
     * Request for auth.
263
     *
264
     * @param ConnectionInterface $connection
265
     * @codeCoverageIgnore
266
     */
267
    protected function sendAuthRequest(ConnectionInterface $connection)
268
    {
269
        $authInfo = array_replace([
270
            'os' => PHP_OS,
271
            'version' => Version::VERSION,
272
        ], $this->configuration->get('auth', []));
273
274
        $connection->write(new Spike('auth', $authInfo));
275
    }
276
277
    /**
278
     * @return Configuration
279
     */
280
    public function getConfiguration()
281
    {
282
        return $this->configuration;
283
    }
284
285
    /**
286
     * {@inheritdoc}
287
     */
288
    public function getControlConnection()
289
    {
290
        return $this->controlConnection;
291
    }
292
293
    /**
294
     * {@inheritdoc}
295
     */
296
    public function getId()
297
    {
298
        return $this->id;
299
    }
300
301
    /**
302
     * {@inheritdoc}
303
     */
304
    public function setId($id)
305
    {
306
        $this->id = $id;
307
    }
308
309
    /**
310
     * {@inheritdoc}
311
     */
312
    public function getActiveAt()
313
    {
314
        return $this->activeAt;
315
    }
316
317
    /**
318
     * {@inheritdoc}
319
     */
320
    public function getEventDispatcher()
321
    {
322
        return $this->eventDispatcher;
323
    }
324
325
    /**
326
     * @param \DateTimeInterface $activeAt
327
     */
328
    public function setActiveAt($activeAt)
329
    {
330
        $this->activeAt = $activeAt;
331
    }
332
333
    /**
334
     * @return LoopInterface
335
     */
336
    public function getEventLoop()
337
    {
338
        return $this->eventLoop;
339
    }
340
341
    /**
342
     * @return Collection|WorkerInterface[]
343
     */
344
    public function getWorkers()
345
    {
346
        return $this->workers;
347
    }
348
349
    /**
350
     * @return Logger
351
     */
352
    public function getLogger()
353
    {
354
        return $this->logger;
355
    }
356
357
    /**
358
     * {@inheritdoc}
359
     */
360
    protected function getDefaultCommands()
361
    {
362
        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...
363
            new Command\ShowProxyHostsCommand($this),
364
            new Command\InitCommand($this),
365
        ]);
366
    }
367
368
    protected function initializeEvents()
369
    {
370
        $this->eventDispatcher->addSubscriber(new Listener\ClientListener());
371
        $this->eventDispatcher->addSubscriber(new Listener\LoggerListener($this));
372
    }
373
374
    /**
375
     * Creates default timers.
376
     *
377
     * @codeCoverageIgnore
378
     */
379
    protected function initializeTimers()
380
    {
381
        $this->addTimer(new Timer\HeartbeatTimer($this));
382
        $this->addTimer(new MemoryWatchTimer($this->getLogger()));
383
    }
384
}