|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Imanghafoori\LaravelMicroscope\Analyzers; |
|
4
|
|
|
|
|
5
|
|
|
use Imanghafoori\LaravelMicroscope\Refactors\EarlyReturns; |
|
6
|
|
|
use Imanghafoori\LaravelMicroscope\Refactors\SyntaxNormalizer; |
|
7
|
|
|
|
|
8
|
|
|
class Refactor |
|
9
|
|
|
{ |
|
10
|
|
|
public const blocksKeyWords = [T_RETURN, T_THROW, T_CONTINUE, T_BREAK]; |
|
11
|
|
|
|
|
12
|
|
|
public static function flatten($tokens) |
|
13
|
|
|
{ |
|
14
|
|
|
$tokens = SyntaxNormalizer::normalizeSyntax($tokens); |
|
15
|
|
|
|
|
16
|
|
|
[$tokens, $changes1] = self::recursiveRefactor($tokens, function ($tokens, $i) { |
|
|
|
|
|
|
17
|
|
|
return Ifs::mergeIfs($tokens, $i); |
|
18
|
|
|
}); |
|
19
|
|
|
|
|
20
|
|
|
[$tokens, $changes2] = self::recursiveRefactor($tokens, function ($tokens, $i) { |
|
|
|
|
|
|
21
|
|
|
return Ifs::else_If($tokens, $i); |
|
22
|
|
|
}); |
|
23
|
|
|
|
|
24
|
|
|
$changes = $changes1 + $changes2; |
|
|
|
|
|
|
25
|
|
|
|
|
26
|
|
|
return EarlyReturns::apply($tokens, $changes); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
public static function saveTokens($path, array $tokens, $test = false) |
|
30
|
|
|
{ |
|
31
|
|
|
$test && ($path = $path.'_flat'); |
|
32
|
|
|
file_put_contents($path, self::toString($tokens)); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
public static function isBlocky(array $codeBlock) |
|
36
|
|
|
{ |
|
37
|
|
|
$isBlocky = false; |
|
38
|
|
|
$depth = 0; |
|
39
|
|
|
|
|
40
|
|
|
foreach ($codeBlock as $token) { |
|
41
|
|
|
$token[0] == '}' && $depth++; |
|
42
|
|
|
$token[0] == '{' && $depth--; |
|
43
|
|
|
if ($depth == 0 && (\in_array($token[0], self::blocksKeyWords))) { |
|
44
|
|
|
$isBlocky = true; |
|
45
|
|
|
} |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
return $isBlocky; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
public static function toString($tokens) |
|
52
|
|
|
{ |
|
53
|
|
|
$string = ''; |
|
54
|
|
|
|
|
55
|
|
|
foreach ($tokens as $token) { |
|
56
|
|
|
$string .= $token[1] ?? $token[0]; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
return $string; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
private static function recursiveRefactor($tokens, $refactor) |
|
63
|
|
|
{ |
|
64
|
|
|
$i = $changes = 0; |
|
65
|
|
|
|
|
66
|
|
|
do { |
|
67
|
|
|
$result = $refactor($tokens, $i); |
|
68
|
|
|
$i++; |
|
69
|
|
|
if ($result) { |
|
70
|
|
|
$tokens = $result; |
|
71
|
|
|
$i = 0; // rewind |
|
72
|
|
|
$changes++; |
|
73
|
|
|
} |
|
74
|
|
|
} while (isset($tokens[$i])); |
|
75
|
|
|
|
|
76
|
|
|
return [$tokens, $changes]; |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|
This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.