Completed
Push — master ( 4e9b37...0f36ee )
by Albert
13s queued 11s
created

HandShakeHandler   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 39
rs 10
c 0
b 0
f 0
wmc 5

1 Method

Rating   Name   Duplication   Size   Complexity  
A handle() 0 29 5
1
<?php
2
3
namespace SwooleTW\Http\Websocket;
4
5
/**
6
 * Class HandShakeHandler
7
 */
8
class HandShakeHandler
9
{
10
    /**
11
     * @see https://www.swoole.co.uk/docs/modules/swoole-websocket-server
12
     *
13
     * @param \Swoole\Http\Request $request
14
     * @param \Swoole\Http\Response $response
15
     *
16
     * @return bool
17
     */
18
    public function handle($request, $response)
19
    {
20
        $socketkey = $request->header['sec-websocket-key'];
21
22
        if (0 === preg_match('#^[+/0-9A-Za-z]{21}[AQgw]==$#', $socketkey) || 16 !== strlen(base64_decode($socketkey))) {
23
            $response->end();
24
25
            return false;
26
        }
27
28
        $headers = [
29
            'Upgrade' => 'websocket',
30
            'Connection' => 'Upgrade',
31
            'Sec-WebSocket-Accept' => base64_encode(sha1($socketkey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true)),
32
            'Sec-WebSocket-Version' => '13',
33
        ];
34
35
        if (isset($request->header['sec-websocket-protocol'])) {
36
            $headers['Sec-WebSocket-Protocol'] = $request->header['sec-websocket-protocol'];
37
        }
38
39
        foreach ($headers as $header => $val) {
40
            $response->header($header, $val);
41
        }
42
43
        $response->status(101);
44
        $response->end();
45
46
        return true;
47
    }
48
}
49