CoreFiles by mySites.guru
LengthCalculator.php66 lines, 1,673 bytes, from Joomla_5.4.10-Stable-Full_Package.zip
Raw History Compare with 5.4.9
md5
a8a268101e433acb41990fa0f3cf70b8
sha1
2cccdbac2f90f9a3226898fc266152ca369a9779
sha256
b24f6cd84d8387692f9cf1a5a4424725a0570cdda0ef09a4c74ccff759876601
<?php

declare(strict_types=1);

namespace CBOR;

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

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

        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(strlen($data), 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 106 releases, Joomla 5.2.0-beta1 to 6.2.0-alpha1. See them all, or every version of this file.