SocketIOParser   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 42
rs 10
c 0
b 0
f 0
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A encode() 0 8 4
A decode() 0 7 1
1
<?php
2
3
namespace SwooleTW\Http\Websocket\SocketIO;
4
5
use SwooleTW\Http\Websocket\Parser;
6
use SwooleTW\Http\Websocket\SocketIO\Strategies\HeartbeatStrategy;
7
8
/**
9
 * Class SocketIOParser
10
 */
11
class SocketIOParser extends Parser
12
{
13
    /**
14
     * Strategy classes need to implement handle method.
15
     */
16
    protected $strategies = [
17
        HeartbeatStrategy::class,
18
    ];
19
20
    /**
21
     * Encode output payload for websocket push.
22
     *
23
     * @param string $event
24
     * @param mixed $data
25
     *
26
     * @return mixed
27
     */
28
    public function encode(string $event, $data)
29
    {
30
        $packet = Packet::MESSAGE . Packet::EVENT;
31
        $shouldEncode = is_array($data) || is_object($data);
32
        $data = $shouldEncode ? json_encode($data) : $data;
33
        $format = $shouldEncode ? '["%s",%s]' : '["%s","%s"]';
34
35
        return $packet . sprintf($format, $event, $data);
36
    }
37
38
    /**
39
     * Decode message from websocket client.
40
     * Define and return payload here.
41
     *
42
     * @param \Swoole\Websocket\Frame $frame
43
     *
44
     * @return array
45
     */
46
    public function decode($frame)
47
    {
48
        $payload = Packet::getPayload($frame->data);
49
50
        return [
51
            'event' => $payload['event'] ?? null,
52
            'data' => $payload['data'] ?? null,
53
        ];
54
    }
55
}
56