WebSocket::checkSecKey()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
namespace Fructify\Reload\Protocol\WebSocket;
3
4
use Fructify\Reload\Response\ResponseWebSocket;
5
6
/**
7
 * Description of WebSocket
8
 *
9
 * @author ricky
10
 */
11
class WebSocket
12
{
13
    const MIN_WS_VERSION = 13;
14
    const MAGIC_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
15
16
    protected $messageQueue;
17
18
    public function __construct()
19
    {
20
        $this->messageQueue = new MessageQueue();
21
    }
22
23
    /**
24
     * @return Frame
25
     */
26
    public function onMessage($data)
27
    {
28
        $this->messageQueue->add($data);
29
30
        return Frame::parse($this->messageQueue);
31
    }
32
33
    public function handshake($request)
34
    {
35
        $key = $request->headers->get('Sec-WebSocket-Key');
36
        if(
37
            strtolower($request->headers->get('Upgrade')) != 'websocket' ||
38
            !$this->checkProtocolVrsion($request) ||
39
            !$this->checkSecKey($key)
40
          ){
41
            return false;
42
        }
43
        $acceptKey = $this->generateAcceptKey($key);
44
        $response = new ResponseWebSocket();
45
        $response->headers->set('Sec-WebSocket-Accept', $acceptKey);
46
47
        return $response;
48
    }
49
50
    protected function generateAcceptKey($key)
51
    {
52
        return base64_encode(sha1($key.static::MAGIC_GUID, true));
53
    }
54
55
    protected function checkSecKey($key)
56
    {
57
        return strlen(base64_decode($key)) == 16;
58
    }
59
60
    protected function checkProtocolVrsion($request)
61
    {
62
        return $request->headers->get('Sec-WebSocket-Version', 0) >= static::MIN_WS_VERSION;
63
    }
64
65
    //put your code here
66
}
67