Completed
Pull Request — master (#286)
by
unknown
10:33
created

HandShakeHandler::handle()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 29
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 16
nc 5
nop 2
dl 0
loc 29
rs 9.4222
c 0
b 0
f 0
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