PluginProbe
Defender Security – Malware Scanner, Login Security & Firewall / 6.3.0
Defender Security – Malware Scanner, Login Security & Firewall v6.3.0
6.3.0 6.2.3 6.2.4 6.2.0 6.2.1 6.2.2 6.1.0 5.3.1 5.4.0 5.4.1 5.5.0 5.5.1 5.6.0 5.6.1 5.6.2 5.7.0 5.7.1 5.7.2 5.8.0 5.8.1 5.9.0 6.0.0 6.0.1 3.0.1 3.1.0 All 141 releases
defender-security / lib / packages / CBOR / LengthCalculator.php

LengthCalculator.php in Defender Security – Malware Scanner, Login Security & Firewall 6.3.0, at lib/packages/CBOR/LengthCalculator.php

78 lines 2.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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