$data * * @return array{int, null|string} */ public static function getLengthOfArray(array $data): array { $length = count($data); return self::computeLength($length); } /** * @return array{int, null|string} */ private static function computeLength(int $length): array { switch (true) { case $length <= 23: return [$length, null]; case $length <= 0xFF: return [CBORObject::LENGTH_1_BYTE, chr($length)]; case $length <= 0xFFFF: return [CBORObject::LENGTH_2_BYTES, self::hex2bin(dechex($length))]; case $length <= 0xFFFFFFFF: return [CBORObject::LENGTH_4_BYTES, self::hex2bin(dechex($length))]; case BigInteger::of($length)->isLessThanOrEqualTo(BigInteger::fromBase('FFFFFFFFFFFFFFFF', 16)): return [CBORObject::LENGTH_8_BYTES, self::hex2bin(dechex($length))]; default: return [CBORObject::LENGTH_INDEFINITE, null]; } } private static function hex2bin(string $data): string { $data = str_pad($data, (int) (2 ** ceil(log(mb_strlen($data, '8bit'), 2))), '0', STR_PAD_LEFT); $result = hex2bin($data); if ($result === false) { throw new InvalidArgumentException('Unable to convert the data'); } return $result; } }