Serializer   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 77
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 24
c 1
b 0
f 0
dl 0
loc 77
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __toString() 0 3 1
A addLong() 0 4 1
A addLongLong() 0 9 2
A pack() 0 8 2
A addString() 0 11 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Sysbot\Bin;
6
7
use BigInteger;
8
use Exception;
9
use Sysbot\Bin\Common\BinaryUtils;
10
11
/**
12
 * Class Serializer
13
 * @package Sysbot\Bin
14
 */
15
class Serializer
16
{
17
18
    use BinaryUtils;
19
20
    /**
21
     * @var string
22
     */
23
    protected string $bytes = '';
24
25
    /**
26
     * @param string $format
27
     * @param mixed|null $value
28
     * @param bool $bigEndian
29
     * @return string
30
     */
31
    public static function pack(string $format, mixed $value = null, bool $bigEndian = false): string
32
    {
33
        /** @var string|false $result */
34
        $result = pack($format, $value);
35
        if ($bigEndian) {
36
            $result = strrev($result);
37
        }
38
        return $result;
39
    }
40
41
    /**
42
     * @param int $value
43
     * @param bool $bigEndian
44
     * @return $this
45
     */
46
    public function addLong(int $value, bool $bigEndian = false): self
47
    {
48
        $this->bytes .= self::pack('V', $value, $bigEndian);
49
        return $this;
50
    }
51
52
    /**
53
     * @param int|BigInteger $value
54
     * @param bool $bigEndian
55
     * @return $this
56
     * @throws Exception
57
     */
58
    public function addLongLong(int|BigInteger $value, bool $bigEndian = false): self
59
    {
60
        $value = BigInteger::of($value);
61
        $data = $value->toBytes();
62
        if (!$bigEndian) {
63
            $data = strrev($data);
64
        }
65
        $this->bytes .= $data;
66
        return $this;
67
    }
68
69
    /**
70
     * @param string $str
71
     * @return $this
72
     */
73
    public function addString(string $str): self
74
    {
75
        $len = strlen($str);
76
        $data = chr($len);
77
        if (253 < $len) {
78
            $data = chr(254) . substr(self::pack('V', $len), 0, 3);
79
            $len++;
80
        }
81
        $data .= $str . pack('@' . self::positiveModulo(-$len - 1, 4));
82
        $this->bytes .= $data;
83
        return $this;
84
    }
85
86
    /**
87
     * @return string
88
     */
89
    public function __toString(): string
90
    {
91
        return $this->bytes;
92
    }
93
94
}