| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
/* |
| 6 |
* The MIT License (MIT) |
| 7 |
* |
| 8 |
* Copyright (c) 2018-2020 Spomky-Labs |
| 9 |
* |
| 10 |
* This software may be modified and distributed under the terms |
| 11 |
* of the MIT license. See the LICENSE file for details. |
| 12 |
*/ |
| 13 |
|
| 14 |
namespace WP_DEFENDER_VENDOR\CBOR; |
| 15 |
|
| 16 |
use WP_DEFENDER_VENDOR\Brick\Math\BigInteger; |
| 17 |
use function chr; |
| 18 |
use function count; |
| 19 |
use InvalidArgumentException; |
| 20 |
use const STR_PAD_LEFT; |
| 21 |
|
| 22 |
final class LengthCalculator |
| 23 |
{ |
| 24 |
/** |
| 25 |
* @return array{int, null|string} |
| 26 |
*/ |
| 27 |
public static function getLengthOfString(string $data): array |
| 28 |
{ |
| 29 |
$length = mb_strlen($data, '8bit'); |
| 30 |
|
| 31 |
return self::computeLength($length); |
| 32 |
} |
| 33 |
|
| 34 |
/** |
| 35 |
* @param array<int|string, mixed> $data |
| 36 |
* |
| 37 |
* @return array{int, null|string} |
| 38 |
*/ |
| 39 |
public static function getLengthOfArray(array $data): array |
| 40 |
{ |
| 41 |
$length = count($data); |
| 42 |
|
| 43 |
return self::computeLength($length); |
| 44 |
} |
| 45 |
|
| 46 |
/** |
| 47 |
* @return array{int, null|string} |
| 48 |
*/ |
| 49 |
private static function computeLength(int $length): array |
| 50 |
{ |
| 51 |
switch (true) { |
| 52 |
case $length <= 23: |
| 53 |
return [$length, null]; |
| 54 |
case $length <= 0xFF: |
| 55 |
return [CBORObject::LENGTH_1_BYTE, chr($length)]; |
| 56 |
case $length <= 0xFFFF: |
| 57 |
return [CBORObject::LENGTH_2_BYTES, self::hex2bin(dechex($length))]; |
| 58 |
case $length <= 0xFFFFFFFF: |
| 59 |
return [CBORObject::LENGTH_4_BYTES, self::hex2bin(dechex($length))]; |
| 60 |
case BigInteger::of($length)->isLessThanOrEqualTo(BigInteger::fromBase('FFFFFFFFFFFFFFFF', 16)): |
| 61 |
return [CBORObject::LENGTH_8_BYTES, self::hex2bin(dechex($length))]; |
| 62 |
default: |
| 63 |
return [CBORObject::LENGTH_INDEFINITE, null]; |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
private static function hex2bin(string $data): string |
| 68 |
{ |
| 69 |
$data = str_pad($data, (int) (2 ** ceil(log(mb_strlen($data, '8bit'), 2))), '0', STR_PAD_LEFT); |
| 70 |
$result = hex2bin($data); |
| 71 |
if ($result === false) { |
| 72 |
throw new InvalidArgumentException('Unable to convert the data'); |
| 73 |
} |
| 74 |
|
| 75 |
return $result; |
| 76 |
} |
| 77 |
} |
| 78 |
|