Server::handleControlConnection()   B
last analyzed

Complexity

Conditions 6
Paths 1

Size

Total Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 1
nop 1
dl 0
loc 39
rs 8.6737
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\Server;
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\Server as Socket;
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\ClientInterface;
25
use Spike\Common\Logger\Logger;
26
use Spike\Common\Protocol\Spike;
27
use Spike\Common\Timer\MemoryWatchTimer;
28
use Spike\Common\Timer\TimersAware;
29
use Spike\Server\ChunkServer\ChunkServerCollection;
30
use Spike\Server\ChunkServer\ChunkServerInterface;
31
use Spike\Server\Event\ClientTerminateEvent;
32
use Spike\Server\Event\Events;
33
use Spike\Server\Event\FilterActionHandlerEvent;
34
use Symfony\Component\Console\Application;
35
use Symfony\Component\Console\Input\InputInterface;
36
use Symfony\Component\Console\Input\InputOption;
37
use Symfony\Component\Console\Output\OutputInterface;
38
39
class Server extends Application implements ServerInterface
40
{
41
    use TimersAware;
42
43
    /**
44
     * @var string
45
     */
46
    const LOGO = <<<EOT
47
 _____   _____   _   _   _    _____   _____  
48
/  ___/ |  _  \ | | | | / /  | ____| |  _  \ 
49
| |___  | |_| | | | | |/ /   | |__   | | | | 
50
\___  \ |  ___/ | | | |\ \   |  __|  | | | | 
51
 ___| | | |     | | | | \ \  | |___  | |_| | 
52
/_____/ |_|     |_| |_|  \_\ |_____| |_____/ 
53
54
55
EOT;
56
57
    const NAME = 'Spike Server';
58
59
    const VERSION = '0.0.1';
60
61
    /**
62
     * @var Configuration
63
     */
64
    protected $configuration;
65
66
    /**
67
     * @var LoopInterface
68
     */
69
    protected $eventLoop;
70
71
    /**
72
     * @var ChunkServerInterface[]|ChunkServerCollection
73
     */
74
    protected $chunkServers;
75
76
    /**
77
     * @var ClientInterface[]|Collection
78
     */
79
    protected $clients;
80
81
    /**
82
     * @var DispatcherInterface
83
     */
84
    protected $eventDispatcher;
85
86
    /**
87
     * @var Logger
88
     */
89
    protected $logger;
90
91
    public function __construct(Configuration $configuration, LoopInterface $eventLoop = null)
92
    {
93
        $this->configuration = $configuration;
94
        $this->eventLoop = $eventLoop ?: Factory::create();
95
        $this->eventDispatcher = new Dispatcher();
96
        $this->chunkServers = new ChunkServerCollection();
97
        $this->clients = new ArrayCollection();
98
        $this->initializeEvents();
99
        parent::__construct(static::NAME, static::VERSION);
100
    }
101
102
    /**
103
     * {@inheritdoc}
104
     */
105
    public function getHelp()
106
    {
107
        return static::LOGO.parent::getHelp();
108
    }
109
110
    /**
111
     * {@inheritdoc}
112
     */
113
    public function doRun(InputInterface $input, OutputInterface $output)
114
    {
115
        $this->logger = new Logger(
116
            $this->eventLoop,
117
            $this->getConfiguration()->getLogLevel(),
118
            $this->getConfiguration()->getLogFile(),
119
            $output
120
        );
121
        // Execute command if the command name is exists
122
        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...
123
            true === $input->hasParameterOption(array('--help', '-h'), true)
124
        ) {
125
            $exitCode = parent::doRun($input, $output);
126
        } else {
127
            $exitCode = $this->start();
128
        }
129
130
        return $exitCode;
131
    }
132
133
    /**
134
     * {@inheritdoc}
135
     *
136
     * @codeCoverageIgnore
137
     */
138
    public function start()
139
    {
140
        $server = new Socket($this->configuration->getAddress(), $this->eventLoop);
141
        $this->eventDispatcher->dispatch(Events::SERVER_RUN);
142
        $server->on('connection', [$this, 'handleControlConnection']);
143
144
        $this->initializeTimers();
145
        $this->eventLoop->run();
146
147
        return 0;
148
    }
149
150
    /**
151
     * {@inheritdoc}
152
     */
153
    public function stopClient(ClientInterface $client, $closedBy = null)
154
    {
155
        $chunkServers = $this->chunkServers->filter(function(ChunkServerInterface $chunkServer) use ($client){
156
            return $client === $chunkServer->getClient();
157
        });
158
159
        //Fires the client terminate event
160
        $event = new ClientTerminateEvent($client, $chunkServers, $closedBy);
161
        $this->eventDispatcher->dispatch($event);
162
163
        foreach ($chunkServers as $chunkServer) {
164
            //Close the tunnel server and remove it
165
            $chunkServer->stop();
166
            $this->chunkServers->removeElement($chunkServer);
167
        }
168
        $client->close(); //Close the client
169
        $this->clients->removeElement($client); //Removes the client
170
    }
171
172
    /**
173
     * Handle control connection.
174
     *
175
     * @param ConnectionInterface $connection
176
     */
177
    public function handleControlConnection(ConnectionInterface $connection)
178
    {
179
        jsonBuffer($connection, function($messages) use ($connection){
180
            foreach ($messages as $messageData) {
181
                if (!$messageData) {
182
                    continue;
183
                }
184
                $message = Spike::fromArray($messageData);
185
186
                //Fires filter action handler event
187
                $event = new FilterActionHandlerEvent($this, $message, $connection);
188
                $this->eventDispatcher->dispatch($event);
189
                if ($actionHandler = $event->getActionHandler()) {
190
                    try {
191
                        $actionHandler->handle($message);
192
                    } catch (\Exception $exception) {
193
                        //Ignore bad message
194
                    }
195
                }
196
            }
197
        }, function($exception) use ($connection){
198
            $this->eventDispatcher->dispatch(new Event(Events::CONNECTION_ERROR, $this, [
199
                'connection' => $connection,
200
                'exception' => $exception,
201
            ]));
202
        });
203
        //Disconnect
204
        $connection->on('close', function() use($connection){
205
            //If client has been registered and then close it.
206
            $client = $this->clients->filter(function(ClientInterface $client) use ($connection){
207
                return $client->getControlConnection() === $connection;
208
            })->first();
209
            if ($client) {
210
                $this->stopClient($client, ClientTerminateEvent::CLOSED_BY_REMOTE);
211
            } else {
212
                $connection->end();
213
            }
214
        });
215
    }
216
217
    /**
218
     * {@inheritdoc}
219
     */
220
    public function getChunkServers()
221
    {
222
        return $this->chunkServers;
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->chunkServers; of type Spike\Server\ChunkServer...r\ChunkServerCollection adds the type Spike\Server\ChunkServer\ChunkServerInterface[] to the return on line 222 which is incompatible with the return type declared by the interface Spike\Server\ServerInterface::getChunkServers of type Doctrine\Common\Collections\Collection.
Loading history...
223
    }
224
225
    /**
226
     * @return LoopInterface
227
     */
228
    public function getEventLoop()
229
    {
230
        return $this->eventLoop;
231
    }
232
233
    /**
234
     * {@inheritdoc}
235
     */
236
    public function getEventDispatcher()
237
    {
238
        return $this->eventDispatcher;
239
    }
240
241
    /**
242
     * @return Configuration
243
     */
244
    public function getConfiguration()
245
    {
246
        return $this->configuration;
247
    }
248
249
    /**
250
     * Gets all clients.
251
     *
252
     * @return Collection|ClientInterface[]
253
     */
254
    public function getClients()
255
    {
256
        return $this->clients;
257
    }
258
259
    /**
260
     * Gets the client by ID.
261
     *
262
     * @param string $id
263
     *
264
     * @return null|ClientInterface
265
     */
266
    public function getClientById($id)
267
    {
268
        return $this->clients->filter(function(Client $client) use ($id){
269
            return $client->getId() === $id;
270
        })->first();
271
    }
272
273
    /**
274
     * @return Logger
275
     */
276
    public function getLogger()
277
    {
278
        return $this->logger;
279
    }
280
281
    protected function initializeEvents()
282
    {
283
        $this->eventDispatcher->addSubscriber(new Listener\ServerListener());
284
        $this->eventDispatcher->addSubscriber(new Listener\LoggerListener($this));
285
    }
286
287
    /**
288
     * Creates default timers.
289
     *
290
     * @codeCoverageIgnore
291
     */
292
    protected function initializeTimers()
293
    {
294
        $this->addTimer(new Timer\ClientScanTimer($this));
295
        $this->addTimer(new Timer\SummaryWatchTimer($this));
296
        $this->addTimer(new MemoryWatchTimer($this->getLogger()));
297
    }
298
299
    /**
300
     * {@inheritdoc}
301
     */
302
    protected function getDefaultCommands()
303
    {
304
        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\Server\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...
305
            new Command\InitCommand($this),
306
        ]);
307
    }
308
309
    /**
310
     * {@inheritdoc}
311
     */
312
    protected function getDefaultInputDefinition()
313
    {
314
        $definition = parent::getDefaultInputDefinition();
315
        $definition->addOptions([
316
            new InputOption('config', 'c', InputOption::VALUE_OPTIONAL, 'The configuration file, support json,ini,xml and yaml format'),
317
            new InputOption('address', 'a', InputOption::VALUE_REQUIRED, 'The server address'),
318
        ]);
319
320
        return $definition;
321
    }
322
}
323