|
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\TokenStream\Token\BaseToken; |
|
13
|
|
|
use nicoSWD\Rule\TokenStream\Token\TokenBool; |
|
14
|
|
|
use nicoSWD\Rule\TokenStream\Token\TokenRegex; |
|
15
|
|
|
use nicoSWD\Rule\TokenStream\TokenCollection; |
|
16
|
|
|
use nicoSWD\Rule\Parser\Exception\ParserException; |
|
17
|
|
|
use nicoSWD\Rule\Grammar\CallableFunction; |
|
18
|
|
|
|
|
19
|
|
|
final class Test extends CallableFunction |
|
20
|
|
|
{ |
|
21
|
|
|
/** |
|
22
|
|
|
* @param BaseToken $string |
|
23
|
|
|
* @return BaseToken |
|
24
|
|
|
* @throws ParserException |
|
25
|
|
|
*/ |
|
26
|
14 |
|
public function call($string = null): BaseToken |
|
27
|
|
|
{ |
|
28
|
14 |
|
if (!$this->token instanceof TokenRegex) { |
|
29
|
2 |
|
throw new ParserException(sprintf( |
|
30
|
2 |
|
'undefined is not a function at position %d on line %d', |
|
31
|
2 |
|
$this->token->getPosition(), |
|
32
|
2 |
|
$this->token->getLine() |
|
33
|
|
|
)); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
12 |
|
if (!$string) { |
|
37
|
2 |
|
$bool = false; |
|
38
|
|
|
} else { |
|
39
|
|
|
// Remove "g" modifier as is does not exist in PHP |
|
40
|
|
|
// It's also irrelevant in .test() but allowed in JS here |
|
41
|
10 |
|
$pattern = preg_replace_callback( |
|
42
|
10 |
|
'~/[igm]{0,3}$~', |
|
43
|
10 |
|
function (array $modifiers) { |
|
44
|
10 |
|
return str_replace('g', '', $modifiers[0]); |
|
45
|
10 |
|
}, |
|
46
|
|
|
$this->token->getValue() |
|
47
|
|
|
); |
|
48
|
|
|
|
|
49
|
|
|
$subject = $string->getValue(); |
|
50
|
|
|
|
|
51
|
|
|
while ($subject instanceof TokenCollection) { |
|
52
|
|
|
$subject = current($subject->toArray()); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
$bool = (bool) preg_match($pattern, (string) $subject); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
return new TokenBool( |
|
59
|
|
|
$bool, |
|
60
|
|
|
$this->token->getOffset(), |
|
61
|
|
|
$this->token->getStack() |
|
62
|
|
|
); |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|