-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReplaceDecoder.php
More file actions
46 lines (39 loc) · 1.33 KB
/
ReplaceDecoder.php
File metadata and controls
46 lines (39 loc) · 1.33 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
<?php
declare(strict_types=1);
namespace Codewithkyrian\Tokenizers\Decoders;
class ReplaceDecoder extends BaseDecoder
{
public function __construct(
protected ?string $regex,
protected ?string $subString,
protected string $replacement = ''
) {}
public function getConfig(?string $key = null, mixed $default = null): mixed
{
if (null !== $key) {
return match ($key) {
'type' => 'Replace',
'pattern' => $this->regex ? ['Regex' => $this->regex] : ['String' => $this->subString],
'content' => $this->replacement,
default => $default,
};
}
return [
'type' => 'Replace',
'pattern' => $this->regex ? ['Regex' => $this->regex] : ['String' => $this->subString],
'content' => $this->replacement,
];
}
protected function processTokens(array $tokens): array
{
return array_map(function ($token) {
if (null !== $this->regex) {
return preg_replace("/{$this->regex}/u", $this->replacement, (string) $token);
}
if (null !== $this->subString) {
return str_replace($this->subString, $this->replacement, (string) $token);
}
return $token;
}, $tokens);
}
}