CoreFiles by mySites.guru
LengthCalculator.php65 lines, 1,674 bytes, from Joomla_5.1.0-alpha4-Alpha-Full_Package.zip
Raw History Compare with 5.1.0-alpha3
md5
42f166526565b8e9012c8598cfbb474b
sha1
4650938c43508d012f1bd7f6b974cefab79ea164
sha256
9361c5df07956ef37ded8ed604c4bb30b99e220714db6059891ef7449ae7c0e0
<?php

declare(strict_types=1);

namespace CBOR;

use Brick\Math\BigInteger;
use function chr;
use function count;
use InvalidArgumentException;
use const STR_PAD_LEFT;

final class LengthCalculator
{
    /**
     * @return array{int, null|string}
     */
    public static function getLengthOfString(string $data): array
    {
        $length = mb_strlen($data, '8bit');

        return self::computeLength($length);
    }

    /**
     * @param array<int|string, mixed> $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
    {
        return match (true) {
            $length <= 23 => [$length, null],
            $length <= 0xFF => [24, chr($length)],
            $length <= 0xFFFF => [25, self::hex2bin(dechex($length))],
            $length <= 0xFFFFFFFF => [26, self::hex2bin(dechex($length))],
            BigInteger::of($length)->isLessThan(BigInteger::fromBase('FFFFFFFFFFFFFFFF', 16)) => [
                27,
                self::hex2bin(dechex($length)),
            ],
            default => [31, 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;
    }
}

The same content is in 22 releases, Joomla 5.0.0-alpha1 to 5.1.0-alpha4. See them all, or every version of this file.