Passed
Push — master ( e32e27...b9c4c4 )
by Nico
01:27
created

StartsWith::call()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 11
ccs 7
cts 7
cp 1
crap 2
rs 10
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\Parser\Exception\ParserException;
12
use nicoSWD\Rule\TokenStream\Token\BaseToken;
13
use nicoSWD\Rule\TokenStream\Token\TokenBool;
14
use nicoSWD\Rule\TokenStream\Token\TokenInteger;
15
use nicoSWD\Rule\TokenStream\Token\TokenString;
16
17
final class StartsWith extends CallableFunction
18
{
19 6
    public function call(?BaseToken ...$parameters): BaseToken
20
    {
21 6
        if (!$this->token instanceof TokenString) {
22 2
            throw new ParserException('Call to undefined method "startsWith" on non-string');
23
        }
24
25 4
        $needle = $this->parseParameter($parameters, 0);
26 4
        $offset = $this->getOffset($this->parseParameter($parameters, 1));
27 4
        $position = strpos($this->token->getValue(), $needle->getValue(), $offset);
28
29 4
        return new TokenBool($position === $offset);
30
    }
31
32 4
    private function getOffset(?BaseToken $offset): int
33
    {
34 4
        if ($offset instanceof TokenInteger) {
35 2
            $offset = $offset->getValue();
36
        } else {
37 4
            $offset = 0;
38
        }
39
40 4
        return $offset;
41
    }
42
}
43