RequestProxyHandler::handle()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 1
dl 0
loc 18
rs 9.6666
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\Handler;
13
14
use Slince\EventDispatcher\Event;
15
use Spike\Client\Event\Events;
16
use Spike\Common\Exception\InvalidArgumentException;
17
use Spike\Common\Protocol\SpikeInterface;
18
use Spike\Common\Tunnel\HttpTunnel;
19
use Spike\Common\Tunnel\TunnelInterface;
20
use Spike\Client\Worker;
21
22
class RequestProxyHandler extends MessageActionHandler
23
{
24
    /**
25
     * {@inheritdoc}
26
     */
27
    public function handle(SpikeInterface $message)
28
    {
29
        $tunnelInfo = $message->getBody();
30
        $tunnel = $this->client->getConfiguration()->getTunnels()->filter(function(TunnelInterface $tunnel) use ($tunnelInfo){
31
            return $tunnel->match($tunnelInfo);
32
        })->first();
33
        if (!$tunnel) {
34
            throw new InvalidArgumentException('Can not find the matching tunnel');
35
        }
36
        if ($tunnel instanceof HttpTunnel) {
37
            $tunnel->setProxyHost($tunnelInfo['proxyHost']);
38
        }
39
        $client = $this->createWorker($tunnel, $message->getHeader('public-connection-id'));
40
        $this->getEventDispatcher()->dispatch(new Event(Events::REQUEST_PROXY, $this, [
41
            'tunnel' => $tunnel,
42
            'client' => $client,
43
        ]));
44
    }
45
46
    /**
47
     * Creates worker.
48
     *
49
     * @param TunnelInterface $tunnel
50
     * @param $publicConnectionId
51
     *
52
     * @return Worker\WorkerInterface
53
     */
54
    protected function createWorker(TunnelInterface $tunnel, $publicConnectionId)
55
    {
56
        if ($tunnel instanceof HttpTunnel) {
57
            $worker = new Worker\HttpWorker($this->client, $tunnel, $publicConnectionId);
58
        } else {
59
            $worker = new Worker\TcpWorker($this->client, $tunnel, $publicConnectionId);
60
        }
61
        $worker->start();
62
        $this->client->getWorkers()->add($worker);
63
64
        return $worker;
65
    }
66
}