-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathByteFallback.php
62 lines (53 loc) · 1.65 KB
/
ByteFallback.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php
declare(strict_types=1);
namespace Codewithkyrian\Transformers\Decoders;
class ByteFallback extends Decoder
{
/**
* @param array $config
*/
public function __construct(array $config)
{
parent::__construct($config);
}
protected function decodeChain(array $tokens): array
{
$newTokens = [];
$previousByteTokens = [];
foreach ($tokens as $token) {
$bytes = null;
if (strlen($token) === 6 && str_starts_with($token, '<0x') && str_ends_with($token, '>')) {
$byte = hexdec(substr($token, 3, 2));
if (!is_nan($byte)) {
$bytes = $byte;
}
}
if ($bytes !== null) {
$previousByteTokens[] = $bytes;
} else {
if (count($previousByteTokens) > 0) {
$string = $this->bytesToString($previousByteTokens);
$newTokens[] = $string;
$previousByteTokens = [];
}
$newTokens[] = $token;
}
}
if (count($previousByteTokens) > 0) {
$string = $this->bytesToString($previousByteTokens);
$newTokens[] = $string;
}
return $newTokens;
}
/**
* Convert an array of byte values back to a string.
*
* @param array $bytes An array of byte values.
* @return string The resulting string after conversion.
*/
protected function bytesToString(array $bytes): string
{
$binaryString = pack('C*', ...$bytes);
return mb_convert_encoding($binaryString, 'ISO-8859-1');
}
}