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

Replace   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 3
dl 0
loc 60
ccs 28
cts 28
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
B call() 0 29 4
A doRegexReplace() 0 14 2
A splitRegex() 0 6 1
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\Core\CallableFunction;
13
use nicoSWD\Rules\Tokens\TokenRegex;
14
use nicoSWD\Rules\Tokens\TokenString;
15
use nicoSWD\Rules\Tokens\BaseToken;
16
17
final class Replace extends CallableFunction
18
{
19
    /**
20
     * @param BaseToken $search
21
     * @param BaseToken $replace
22
     * @return BaseToken
23
     * @throws \Exception
24
     */
25 10
    public function call($search = null, $replace = null): BaseToken
26
    {
27 10
        $isRegExpr = false;
28
29 10
        if (!$search) {
30 2
            $search = '';
31
        } else {
32 8
            $isRegExpr = ($search instanceof TokenRegex);
33 8
            $search = $search->getValue();
34
        }
35
36 10
        if (!$replace) {
37 4
            $replace = 'undefined';
38
        } else {
39 6
            $replace = $replace->getValue();
40
        }
41
42 10
        if ($isRegExpr) {
43 4
            $value = $this->doRegexReplace($search, $replace);
44
        } else {
45 6
            $value = str_replace($search, $replace, $this->token->getValue());
46
        }
47
48 10
        return new TokenString(
49 10
            $value,
50 10
            $this->token->getOffset(),
51 10
            $this->token->getStack()
52
        );
53
    }
54
55 4
    private function doRegexReplace($search, $replace)
56
    {
57 4
        list ($expression, $modifiers) = $this->splitRegex($search);
58
59 4
        $modifiers = str_replace('g', '', $modifiers, $count);
60 4
        $limit = $count > 0 ? -1 : 1;
61
62 4
        return preg_replace(
63 4
            $expression . $modifiers,
64 4
            $replace,
65 4
            $this->token->getValue(),
66 4
            $limit
67
        );
68
    }
69
70 4
    private function splitRegex(string $regExpr): array
71
    {
72 4
        preg_match('~(.*?/)([img]{0,3})?$~', $regExpr, $match);
73
74 4
        return [$match[1], $match[2]];
75
    }
76
}
77