| Total Complexity | 8 |
| Total Lines | 77 |
| Duplicated Lines | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
| 1 | <?php |
||
| 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 |
||
| 92 | } |
||
| 93 | |||
| 94 | } |