| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace CBOR; |
| 6 |
|
| 7 |
use Brick\Math\BigInteger; |
| 8 |
use function chr; |
| 9 |
use function count; |
| 10 |
use InvalidArgumentException; |
| 11 |
use const STR_PAD_LEFT; |
| 12 |
use function strlen; |
| 13 |
|
| 14 |
final class LengthCalculator |
| 15 |
{ |
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
public static function getLengthOfString(string $data): array |
| 20 |
{ |
| 21 |
$length = strlen($data); |
| 22 |
|
| 23 |
return self::computeLength($length); |
| 24 |
} |
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
public static function getLengthOfArray(array $data): array |
| 32 |
{ |
| 33 |
$length = count($data); |
| 34 |
|
| 35 |
return self::computeLength($length); |
| 36 |
} |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
private static function computeLength(int $length): array |
| 42 |
{ |
| 43 |
return match (true) { |
| 44 |
$length <= 23 => [$length, null], |
| 45 |
$length <= 0xFF => [24, chr($length)], |
| 46 |
$length <= 0xFFFF => [25, self::hex2bin(dechex($length))], |
| 47 |
$length <= 0xFFFFFFFF => [26, self::hex2bin(dechex($length))], |
| 48 |
BigInteger::of($length)->isLessThan(BigInteger::fromBase('FFFFFFFFFFFFFFFF', 16)) => [ |
| 49 |
27, |
| 50 |
self::hex2bin(dechex($length)), |
| 51 |
], |
| 52 |
default => [31, null], |
| 53 |
}; |
| 54 |
} |
| 55 |
|
| 56 |
private static function hex2bin(string $data): string |
| 57 |
{ |
| 58 |
$data = str_pad($data, (int) (2 ** ceil(log(strlen($data), 2))), '0', STR_PAD_LEFT); |
| 59 |
$result = hex2bin($data); |
| 60 |
if ($result === false) { |
| 61 |
throw new InvalidArgumentException('Unable to convert the data'); |
| 62 |
} |
| 63 |
|
| 64 |
return $result; |
| 65 |
} |
| 66 |
} |