-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathByteFallbackDecoder.php
More file actions
51 lines (41 loc) · 1.34 KB
/
ByteFallbackDecoder.php
File metadata and controls
51 lines (41 loc) · 1.34 KB
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
<?php
declare(strict_types=1);
namespace Codewithkyrian\Tokenizers\Decoders;
class ByteFallbackDecoder extends BaseDecoder
{
public function getConfig(?string $key = null, mixed $default = null): mixed
{
if (null !== $key) {
return 'type' === $key ? 'ByteFallback' : $default;
}
return ['type' => 'ByteFallback'];
}
protected function processTokens(array $tokens): array
{
$newTokens = [];
$previousByteTokens = [];
foreach ($tokens as $token) {
$token = (string) $token;
$bytes = null;
if (6 === \strlen($token) && str_starts_with($token, '<0x') && str_ends_with($token, '>')) {
$byte = hexdec(substr($token, 3, 2));
if (!is_nan($byte)) {
$bytes = $byte;
}
}
if (null !== $bytes) {
$previousByteTokens[] = $bytes;
} else {
if (!empty($previousByteTokens)) {
$newTokens[] = pack('C*', ...$previousByteTokens);
$previousByteTokens = [];
}
$newTokens[] = $token;
}
}
if (!empty($previousByteTokens)) {
$newTokens[] = pack('C*', ...$previousByteTokens);
}
return $newTokens;
}
}