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

ServerHandshake   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 10
lcom 0
cbo 4
dl 0
loc 55
ccs 25
cts 25
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A sign() 0 14 3
C verify() 0 34 7
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\Rfc6455\Handshake;
13
use Nekland\Woketo\Exception\WebsocketException;
14
use Nekland\Woketo\Exception\WebsocketVersionException;
15
use Nekland\Woketo\Http\Request;
16
use Nekland\Woketo\Http\Response;
17
18
19
/**
20
 * Class ServerHandshake
21
 *
22
 * This class is highly inspired by ratchetphp/RFC6455.
23
 */
24
class ServerHandshake implements HandshakeInterface
25
{
26
    const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
27
    const SUPPORTED_VERSIONS = [13];
28
29 5
    public function sign($key, Response $response = null)
30
    {
31 5
        if ($key instanceof Request) {
32 4
            $key = $key->getHeader('Sec-WebSocket-Key');
33
        }
34
35 5
        $sign = \base64_encode(\sha1($key . ServerHandshake::GUID, true));
36
37 5
        if (null !== $response) {
38 4
            $response->addHeader('Sec-WebSocket-Accept', $sign);
39
        }
40
41 5
        return $sign;
42
    }
43
44 10
    public function verify(Request $request)
45
    {
46 10
        if ($request->getHttpVersion() !== 'HTTP/1.1') {
47 1
            throw new WebsocketException(
48 1
                \sprintf('Wrong http version, HTTP/1.1 expected, "%s" received.', $request->getHttpVersion())
49
            );
50
        }
51
52 9
        if ($request->getMethod() !== 'GET') {
53 1
            throw new WebsocketException(
54 1
                \sprintf('Wrong http method, GET expected, "%" received.', $request->getMethod())
55
            );
56
        }
57
58 8
        $headers = $request->getHeaders();
59 8
        if (empty($headers['Sec-WebSocket-Key'])) {
60 1
            throw new WebsocketException(
61 1
                \sprintf('Missing websocket key header.')
62
            );
63
        }
64
65 7
        if (empty($headers['Upgrade']) || 'websocket' !== \strtolower($headers['Upgrade'])) {
66 1
            throw new WebsocketException(
67 1
                \sprintf('Wrong or missing upgrade header.')
68
            );
69
        }
70
71 6
        $version = $headers->get('Sec-WebSocket-Version');
72 6
        if (!\in_array($version, ServerHandshake::SUPPORTED_VERSIONS)) {
73 1
            throw new WebsocketVersionException(sprintf('Version %s not supported by Woketo for now.', $version));
74
        }
75
76 5
        return true;
77
    }
78
}