Lines
90.00%
9 / 10
Functions and Methods
80.00%
4 / 5
Classes and Traits
0.00%
0 / 1
| Name | Lines | Functions and Methods | CRAP | Classes and Traits | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| PacketBytes | 90.00% | 9 / 10 | 80.00% | 4 / 5 | 6.04 | 0.00% | 0 / 1 | |||
| __construct | 0.00% | 0 / 1 | 0.00% | 0 / 1 | 2 | |||||
| assemblePacket | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| encodeString | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| encodeUint16 | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| encodeRemainingLength | 100.00% | 6 / 6 | 100.00% | 1 / 1 | 2 | |||||
| 1 | <?php | |
| 2 | ||
| 3 | declare(strict_types=1); | |
| 4 | ||
| 5 | namespace Stewart\Mqtt\Packet; | |
| 6 | ||
| 7 | final class PacketBytes | |
| 8 | { | |
| 9 | public const int MAX_REMAINING_LENGTH = 268_435_455; | |
| 10 | ||
| 11 | private const int LENGTH_DIGIT_BASE = 128; | |
| 12 | ||
| 13 | private function __construct() {} | |
| 14 | ||
| 15 | public static function assemblePacket(PacketType $type, int $flags, string $body): string | |
| 16 | { | |
| 17 | return pack('C', ($type->value << 4) | $flags) . self::encodeRemainingLength(\strlen($body)) . $body; | |
| 18 | } | |
| 19 | ||
| 20 | public static function encodeString(string $value): string | |
| 21 | { | |
| 22 | return pack('n', \strlen($value)) . $value; | |
| 23 | } | |
| 24 | ||
| 25 | public static function encodeUint16(int $value): string | |
| 26 | { | |
| 27 | return pack('n', $value); | |
| 28 | } | |
| 29 | ||
| 30 | public static function encodeRemainingLength(int $length): string | |
| 31 | { | |
| 32 | $encoded = ''; | |
| 33 | ||
| 34 | do { | |
| 35 | $digit = $length % self::LENGTH_DIGIT_BASE; | |
| 36 | $length = intdiv($length, self::LENGTH_DIGIT_BASE); | |
| 37 | $encoded .= pack('C', $length > 0 ? $digit | self::LENGTH_DIGIT_BASE : $digit); | |
| 38 | } while ($length > 0); | |
| 39 | ||
| 40 | return $encoded; | |
| 41 | } | |
| 42 | } |