CoreFiles by mySites.guru
LengthCalculator.php66 lines, 1,673 bytes, from Joomla_6.2.1-Stable-Full_Package.zip
Raw History Compare with 6.2.0
md5
0bbce40e2644c284668ac33c8c656eb4
sha1
a7abee23e962ccf47db8432109752b1042bdb4a3
sha256
2fe5f510a41e7837b9461a6c7826955ef9a2040faf8852cd192e32d789f957d8
<?php

declare(strict_types=1);

namespace CBOR;

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

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 11 releases, Joomla 6.2.0-alpha2 to 6.3.0-alpha1. See them all, or every version of this file.