Completed
Pull Request — master (#100)
by Maxime
02:25
created

AbstractConnection::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 1
1
<?php
2
3
/**
4
 * This file is a part of Woketo package.
5
 *
6
 * (c) Nekland <[email protected]>
7
 *
8
 * For the full license, take a look to the LICENSE file
9
 * on the root directory of this project
10
 */
11
12
namespace Nekland\Woketo\Core;
13
14
use Nekland\Woketo\Exception\WebsocketException;
15
use Nekland\Woketo\Message\MessageHandlerInterface;
16
use Nekland\Woketo\Rfc6455\Handshake\HandshakeInterface;
17
use Nekland\Woketo\Rfc6455\MessageProcessor;
18
use Psr\Log\LoggerAwareTrait;
19
use React\Socket\Connection;
20
21
abstract class AbstractConnection
22
{
23
    use LoggerAwareTrait;
24
    /**
25
     * @var Connection
26
     */
27
    protected $stream;
28
29
    /**
30
     * @var MessageProcessor
31
     */
32
    protected $messageProcessor;
33
34
    /**
35
     * @var HandshakeInterface
36
     */
37
    protected $handshake;
38
39
    /**
40
     * @var bool
41
     */
42
    protected $handshakeDone;
43
44
    /**
45
     * @var MessageHandlerInterface
46
     */
47
    protected $handler;
48
49 2
    public function __construct(MessageProcessor $messageProcessor, HandshakeInterface $handshake = null)
50
    {
51 2
        $this->handshake = $handshake;
52 2
        $this->messageProcessor = $messageProcessor;
53 2
    }
54
55
    protected function onMessage(string $data)
56
    {
57
        try {
58
            if (!$this->handshakeDone) {
59
                $this->processHandshake($data);
60
            } else {
61
                $this->processMessage($data);
62
            }
63
64
            return;
65
        } catch (WebsocketException $e) {
66
            $this->messageProcessor->close($this->stream);
67
            $this->logger->notice('Connection to ' . $this->getIp() . ' closed with error : ' . $e->getMessage());
68
            $this->handler->onError($e, $this);
69
        }
70
    }
71
72
    protected abstract function processHandshake(string $data);
0 ignored issues
show
Coding Style introduced by
The abstract declaration must precede the visibility declaration
Loading history...
73
    protected abstract function processMessage(string $data);
0 ignored issues
show
Coding Style introduced by
The abstract declaration must precede the visibility declaration
Loading history...
74
75
    /**
76
     * @return string
77
     */
78
    public function getIp()
79
    {
80
        return $this->stream->getRemoteAddress();
81
    }
82
83
    /**
84
     * @return \Psr\Log\LoggerInterface
85
     */
86
    public function getLogger()
87
    {
88
        return $this->logger;
89
    }
90
}