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

StartsWith   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 24
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 24
ccs 12
cts 12
cp 1
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A call() 0 11 2
A getOffset() 0 9 2
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