Completed
Push — master ( 2a4290...c23846 )
by Nico
01:31
created

Test::call()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 38
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 38
ccs 13
cts 13
cp 1
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 22
nc 3
nop 1
crap 4
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\Rules\Grammar\JavaScript\Methods;
11
12
use nicoSWD\Rules\AST\TokenCollection;
13
use nicoSWD\Rules\Core\CallableFunction;
14
use nicoSWD\Rules\Exceptions\ParserException;
15
use nicoSWD\Rules\Tokens\TokenBool;
16
use nicoSWD\Rules\Tokens\TokenRegex;
17
use nicoSWD\Rules\Tokens\BaseToken;
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