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