Completed
Push — master ( 143878...f45699 )
by Taosikai
14:33
created

Client::close()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 14
rs 9.2
cc 4
eloc 9
nc 8
nop 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
    public function __construct(Configuration $configuration, LoopInterface $eventLoop = null)
101
    {
102
        $this->configuration = $configuration;
103
        $this->eventLoop = $eventLoop ?: Factory::create();
104
        $this->eventDispatcher = new Dispatcher();
105
        $this->workers = new ArrayCollection();
106
        $this->initializeEvents();
107
        parent::__construct(static::NAME, Version::VERSION);
108
    }
109
110
    /**
111
     * {@inheritdoc}
112
     */
113
    public function getHelp()
114
    {
115
        return static::LOGO.parent::getHelp();
116
    }
117
118
    /**
119
     * {@inheritdoc}
120
     *
121
     * @codeCoverageIgnore
122
     */
123
    public function doRun(InputInterface $input, OutputInterface $output)
124
    {
125
        $this->logger = new Logger(
126
            $this->eventLoop,
127
            $this->getConfiguration()->getLogLevel(),
128
            $this->getConfiguration()->getLogFile(),
129
            $output
130
        );
131
        // Execute command if the command name is exists
132
        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...
133
            true === $input->hasParameterOption(array('--help', '-h'), true)
134
        ) {
135
            $exitCode = parent::doRun($input, $output);
136
        } else {
137
            $exitCode = $this->start();
138
        }
139
140
        return $exitCode;
141
    }
142
143
    /**
144
     * Start Connect to Server.
145
     *
146
     * @return int
147
     */
148
    protected function start()
149
    {
150
        $connector = new Connector($this->eventLoop);
151
        $connector->connect($this->configuration->getServerAddress())->then(function($connection){
152
            $this->initializeTimers();
153
            $this->handleControlConnection($connection);
154
        }, function(){
155
            $this->eventDispatcher->dispatch(new Event(Events::CANNOT_CONNECT_SERVER, $this));
156
        });
157
        $this->eventDispatcher->dispatch(Events::CLIENT_RUN);
158
        $this->eventLoop->run();
159
160
        return 0;
161
    }
162
163
    /**
164
     * Handles the control connection.
165
     *
166
     * @param ConnectionInterface $connection
167
     * @codeCoverageIgnore
168
     */
169
    protected function handleControlConnection(ConnectionInterface $connection)
170
    {
171
        $this->controlConnection = $connection;
172
        //Emit the event
173
        $this->eventDispatcher->dispatch(new Event(Events::CLIENT_CONNECT, $this, [
174
            'connection' => $connection,
175
        ]));
176
        //Sends auth request
177
        $this->sendAuthRequest($connection);
178
        //Distinct from server
179
        $connection->on('close', function(){
180
            $this->eventDispatcher->dispatch(new Event(Events::DISCONNECT_FROM_SERVER, $this));
181
        });
182
183
        jsonBuffer($connection, function($messages) use ($connection){
184
            foreach ($messages as $messageData) {
185
                if (!$messageData) {
186
                    continue;
187
                }
188
                $message = Spike::fromArray($messageData);
189
190
                //Fires filter action handler event
191
                $event = new FilterActionHandlerEvent($this, $message, $connection);
192
                $this->eventDispatcher->dispatch($event);
193
194
                if ($actionHandler = $event->getActionHandler()) {
195
                    $actionHandler->handle($message);
196
                }
197
            }
198
        }, function($exception) use ($connection){
199
            $this->eventDispatcher->dispatch(new Event(Events::CONNECTION_ERROR, $this, [
200
                'connection' => $connection,
201
                'exception' => $exception,
202
            ]));
203
        });
204
    }
205
206
    /**
207
     * Request for auth.
208
     *
209
     * @param ConnectionInterface $connection
210
     * @codeCoverageIgnore
211
     */
212
    protected function sendAuthRequest(ConnectionInterface $connection)
213
    {
214
        $authInfo = array_replace([
215
            'os' => PHP_OS,
216
            'version' => Version::VERSION,
217
        ], $this->configuration->get('auth', []));
218
219
        $connection->write(new Spike('auth', $authInfo));
220
    }
221
222
    /**
223
     * @return Configuration
224
     */
225
    public function getConfiguration()
226
    {
227
        return $this->configuration;
228
    }
229
230
    /**
231
     * {@inheritdoc}
232
     */
233
    public function getControlConnection()
234
    {
235
        return $this->controlConnection;
236
    }
237
238
    /**
239
     * {@inheritdoc}
240
     */
241
    public function getId()
242
    {
243
        return $this->id;
244
    }
245
246
    /**
247
     * {@inheritdoc}
248
     */
249
    public function setId($id)
250
    {
251
        $this->id = $id;
252
    }
253
254
    /**
255
     * {@inheritdoc}
256
     */
257
    public function getActiveAt()
258
    {
259
        return $this->activeAt;
260
    }
261
262
    /**
263
     * {@inheritdoc}
264
     */
265
    public function getEventDispatcher()
266
    {
267
        return $this->eventDispatcher;
268
    }
269
270
    /**
271
     * @param \DateTimeInterface $activeAt
272
     */
273
    public function setActiveAt($activeAt)
274
    {
275
        $this->activeAt = $activeAt;
276
    }
277
278
    /**
279
     * @return LoopInterface
280
     */
281
    public function getEventLoop()
282
    {
283
        return $this->eventLoop;
284
    }
285
286
    /**
287
     * @return Collection|WorkerInterface[]
288
     */
289
    public function getWorkers()
290
    {
291
        return $this->workers;
292
    }
293
294
    /**
295
     * @return Logger
296
     */
297
    public function getLogger()
298
    {
299
        return $this->logger;
300
    }
301
302
    /**
303
     * {@inheritdoc}
304
     */
305
    protected function getDefaultCommands()
306
    {
307
        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...
308
            new Command\ShowProxyHostsCommand($this),
309
            new Command\InitCommand($this),
310
        ]);
311
    }
312
313
    protected function initializeEvents()
314
    {
315
        $this->eventDispatcher->addSubscriber(new ClientListener());
316
        $this->eventDispatcher->addSubscriber(new LoggerListener($this));
317
    }
318
319
    /**
320
     * Creates default timers.
321
     *
322
     * @codeCoverageIgnore
323
     */
324
    protected function initializeTimers()
325
    {
326
        $this->addTimer(new Timer\Heartbeat($this));
327
    }
328
}