|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* @license http://opensource.org/licenses/mit-license.php MIT |
|
5
|
|
|
* @link https://github.com/nicoSWD |
|
6
|
|
|
* @author Nicolas Oelgart <[email protected]> |
|
7
|
|
|
*/ |
|
8
|
|
|
namespace nicoSWD\Rule\Grammar\JavaScript\Methods; |
|
9
|
|
|
|
|
10
|
|
|
use nicoSWD\Rule\Grammar\CallableFunction; |
|
11
|
|
|
use nicoSWD\Rule\TokenStream\Token\BaseToken; |
|
12
|
|
|
use nicoSWD\Rule\TokenStream\Token\TokenRegex; |
|
13
|
|
|
use nicoSWD\Rule\TokenStream\Token\TokenString; |
|
14
|
|
|
|
|
15
|
|
|
final class Replace extends CallableFunction |
|
16
|
|
|
{ |
|
17
|
10 |
|
public function call(?BaseToken ...$parameters): BaseToken |
|
18
|
|
|
{ |
|
19
|
10 |
|
$isRegExpr = false; |
|
20
|
10 |
|
$search = $this->parseParameter($parameters, numParam: 0); |
|
21
|
|
|
|
|
22
|
10 |
|
if (!$search) { |
|
23
|
2 |
|
$search = ''; |
|
24
|
|
|
} else { |
|
25
|
8 |
|
$isRegExpr = ($search instanceof TokenRegex); |
|
26
|
8 |
|
$search = $search->getValue(); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
10 |
|
$replace = $this->parseParameter($parameters, numParam: 1); |
|
30
|
|
|
|
|
31
|
10 |
|
if (!$replace) { |
|
32
|
4 |
|
$replace = 'undefined'; |
|
33
|
|
|
} else { |
|
34
|
6 |
|
$replace = $replace->getValue(); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
10 |
|
if ($isRegExpr) { |
|
38
|
4 |
|
$value = $this->doRegexReplace($search, $replace); |
|
39
|
|
|
} else { |
|
40
|
6 |
|
$value = str_replace($search, $replace, $this->token->getValue()); |
|
|
|
|
|
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
10 |
|
return new TokenString($value); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
4 |
|
private function doRegexReplace(string $search, string $replace): string |
|
47
|
|
|
{ |
|
48
|
4 |
|
[$expression, $modifiers] = $this->splitRegex($search); |
|
49
|
|
|
|
|
50
|
4 |
|
$modifiers = str_replace('g', '', $modifiers, $count); |
|
51
|
4 |
|
$limit = $count > 0 ? -1 : 1; |
|
52
|
|
|
|
|
53
|
4 |
|
return preg_replace( |
|
54
|
4 |
|
$expression . $modifiers, |
|
55
|
4 |
|
$replace, |
|
56
|
4 |
|
$this->token->getValue(), |
|
|
|
|
|
|
57
|
4 |
|
$limit |
|
58
|
|
|
); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
4 |
|
private function splitRegex(string $regExpr): array |
|
62
|
|
|
{ |
|
63
|
4 |
|
preg_match('~(?<regex>.*?/)(?<modifiers>[img]{0,3})?$~', $regExpr, $match); |
|
64
|
|
|
|
|
65
|
4 |
|
return [$match['regex'], $match['modifiers']]; |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|