Test::call()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 29
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 15
nc 3
nop 1
dl 0
loc 29
ccs 15
cts 15
cp 1
crap 4
rs 9.7666
c 0
b 0
f 0
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\TokenStream\Token\BaseToken;
11
use nicoSWD\Rule\TokenStream\Token\TokenBool;
12
use nicoSWD\Rule\TokenStream\Token\TokenRegex;
13
use nicoSWD\Rule\TokenStream\TokenCollection;
14
use nicoSWD\Rule\Parser\Exception\ParserException;
15
use nicoSWD\Rule\Grammar\CallableFunction;
16
17
final class Test extends CallableFunction
18
{
19 14
    public function call(?BaseToken ...$parameters): BaseToken
20
    {
21 14
        if (!$this->token instanceof TokenRegex) {
0 ignored issues
show
Bug Best Practice introduced by
The property token does not exist on nicoSWD\Rule\Grammar\JavaScript\Methods\Test. Did you maybe forget to declare it?
Loading history...
22 2
            throw new ParserException('undefined is not a function');
23
        }
24
25 12
        $string = $this->parseParameter($parameters, numParam: 0);
26
27 12
        if (!$string) {
28 2
            $bool = false;
29
        } else {
30
            // Remove "g" modifier as is does not exist in PHP
31
            // It's also irrelevant in .test() but allowed in JS here
32 10
            $pattern = preg_replace_callback(
33 10
                '~/[igm]{0,3}$~',
34
                fn (array $modifiers) => str_replace('g', '', $modifiers[0]),
35 10
                $this->token->getValue()
36 10
            );
37 10
38
            $subject = $string->getValue();
39
40 10
            while ($subject instanceof TokenCollection) {
41
                $subject = current($subject->toArray());
42 10
            }
43 2
44
            $bool = (bool) preg_match($pattern, (string) $subject);
45
        }
46 10
47
        return TokenBool::fromBool($bool);
48
    }
49
}
50