RegisterTunnelHandler::handle()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 5
nop 1
dl 0
loc 32
rs 9.408
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\Handler;
13
14
use Spike\Common\Protocol\Spike;
15
use Spike\Common\Protocol\SpikeInterface;
16
use Spike\Common\Tunnel\HttpTunnel;
17
use Spike\Common\Tunnel\TunnelFactory;
18
use Spike\Common\Tunnel\TunnelInterface;
19
use Spike\Server\ChunkServer;
20
21
class RegisterTunnelHandler extends RequireAuthHandler
22
{
23
    /**
24
     * {@inheritdoc}
25
     */
26
    public function handle(SpikeInterface $message)
27
    {
28
        parent::handle($message);
29
        $tunnelInfo = $message->getBody();
30
        $chunkServer = $this->server->getChunkServers()->findByTunnelInfo($tunnelInfo);
31
        if (!$chunkServer) {
32
            $tunnel = TunnelFactory::fromArray($tunnelInfo);
33
            try {
34
                $chunkServer = $this->createChunkServer($tunnel);
35
                $chunkServer->start();
36
37
                $response = new Spike('register_tunnel_response', $tunnel->toArray(), [
38
                    'code' => 200,
39
                ]);
40
            } catch (\Exception $exception) {
41
                $body = array_merge($tunnel->toArray(), [
42
                    'error' => iconv ('UTF-8', 'UTF-8//IGNORE', $exception->getMessage())
43
                ]);
44
                $response = new Spike('register_tunnel_response', $body, [
45
                    'code' => $exception->getCode() ?: 1,
46
                ]);
47
            }
48
        } else {
49
            $body = array_merge($tunnelInfo, [
50
                'error' => 'The tunnel has been registered'
51
            ]);
52
            $response = new Spike('register_tunnel_response', $body, [
53
                'code' => 1,
54
            ]);
55
        }
56
        $this->connection->write($response);
57
    }
58
59
    /**
60
     * Creates a tunnel server for the tunnel.
61
     *
62
     * @param TunnelInterface $tunnel
63
     *
64
     * @return ChunkServer\ChunkServerInterface
65
     */
66
    protected function createChunkServer(TunnelInterface $tunnel)
67
    {
68
        if ($tunnel instanceof HttpTunnel) {
69
            $chunkServer = new ChunkServer\HttpChunkServer($this->server, $this->client, $tunnel);
70
        } else {
71
            $chunkServer = new ChunkServer\TcpChunkServer($this->server, $this->client, $tunnel);
72
        }
73
        $this->server->getChunkServers()->add($chunkServer);
74
75
        return $chunkServer;
76
    }
77
}