CheckRouteCalls::redirectRouteTokens()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Imanghafoori\LaravelMicroscope\Checks;
4
5
use Imanghafoori\LaravelMicroscope\Analyzers\FunctionCall;
6
use Imanghafoori\LaravelMicroscope\ErrorReporters\ErrorPrinter;
7
8
class CheckRouteCalls
9
{
10
    public static $checkedRouteCallsNum = 0;
11
12
    public static $skippedRouteCallsNum = 0;
13
14
    public static function check($tokens, $absFilePath)
15
    {
16
        // we skip the very first tokens: '<?php '
17
        $i = 4;
18
        // we skip the very end of the file.
19
        $total = \count($tokens) - 3;
20
        while ($i < $total) {
21
            $index = FunctionCall::isGlobalCall('route', $tokens, $i);
22
            $index = $index ?: self::checkForRedirectRoute($tokens, $i);
23
24
            if (! $index) {
25
                $i++;
26
                continue;
27
            }
28
29
            $params = FunctionCall::readParameters($tokens, $i);
30
31
            $param1 = null;
32
            // it should be a hard-coded string which is not concatinated like this: 'hi'. $there
33
            $paramTokens = $params[0] ?? ['_', '_'];
34
            FunctionCall::isSolidString($paramTokens) && ($param1 = $params[0]);
35
36
            if ($param1) {
37
                self::$checkedRouteCallsNum++;
38
                self::checkRouteExists($tokens[$index][2], $param1[0][1], $absFilePath);
39
            } else {
40
                self::$skippedRouteCallsNum++;
41
            }
42
            $i++;
43
        }
44
45
        return $tokens;
46
    }
47
48
    public static function printError($value, $absPath, $lineNumber)
49
    {
50
        $p = app(ErrorPrinter::class);
51
        $p->route("route($value)", "route name $value does not exist: ", '  <=== is wrong', $absPath, $lineNumber);
52
    }
53
54
    public static function checkRouteExists($line, $routeName, $absPath)
55
    {
56
        $matchedRoute = app('router')->getRoutes()->getByName(\trim($routeName, '\'\"'));
57
        is_null($matchedRoute) && self::printError($routeName, $absPath, $line);
58
    }
59
60
    private static function redirectRouteTokens()
61
    {
62
        return [
63
            '(',
64
            [T_STRING, 'route'],
65
            [T_OBJECT_OPERATOR, '->'],
66
            ')',
67
            '(',
68
            [T_STRING, 'redirect'],
69
        ];
70
    }
71
72
    private static function checkForRedirectRoute($tokens, $i)
73
    {
74
        $index1 = FunctionCall::checkTokens(self::redirectRouteTokens(), $tokens, $i);
75
        $index1 = $index1 ?: FunctionCall::isStaticCall('route', $tokens, $i, 'Redirect');
76
        $index1 = $index1 ?: FunctionCall::isStaticCall('route', $tokens, $i, 'URL');
77
78
        return array_pop($index1);
79
    }
80
}
81