Parser   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 6
eloc 27
c 2
b 0
f 0
dl 0
loc 52
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A encode() 0 17 3
A decode() 0 19 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Sysbot\Bin;
6
7
use Exception;
8
use Sysbot\Bin\Constants\Formats;
9
10
/**
11
 * Class Parser
12
 * @package Sysbot\Bin
13
 */
14
class Parser
15
{
16
17
    /**
18
     * @param string $bytes
19
     * @param array $data
20
     * @return array<array{format: string, big_endian?: bool}>
21
     * @throws Exception
22
     */
23
    public static function decode(string $bytes, array $data): array
24
    {
25
        $deserializer = new Deserializer($bytes);
26
        $result = [];
27
        $index = 0;
28
        foreach ($data as $value) {
29
            $format = $value['format'] ?? null;
30
            if (empty($format)) {
31
                continue;
32
            }
33
            $bigEndian = $value['big_endian'] ?? false;
34
            $result[$index] = match ($format) {
35
                Formats::LONG => $deserializer->readLong($bigEndian),
36
                Formats::LONG_LONG => $deserializer->readLongLong($bigEndian),
37
                Formats::STRING => $deserializer->readString()
38
            };
39
            $index++;
40
        }
41
        return $result;
42
    }
43
44
    /**
45
     * @param array<array{format: string, value: mixed, big_endian?: bool}> $data
46
     * @return string
47
     * @throws Exception
48
     */
49
    public static function encode(array $data): string
50
    {
51
        $serializer = new Serializer();
52
        foreach ($data as $value) {
53
            $format = $value['format'] ?? null;
54
            $content = $value['value'] ?? null;
55
            if (empty($format)) {
56
                continue;
57
            }
58
            $bigEndian = $value['big_endian'] ?? false;
59
            match ($format) {
60
                Formats::LONG => $serializer->addLong($content ?? 0, $bigEndian),
61
                Formats::LONG_LONG => $serializer->addLongLong($content ?? 0, $bigEndian),
62
                Formats::STRING => $serializer->addString((string)$content)
63
            };
64
        }
65
        return (string)$serializer;
66
    }
67
68
}