This repository has been archived by the owner on May 24, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathCodeOptimizer.php
96 lines (80 loc) · 2 KB
/
CodeOptimizer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<?php
$opts = getopt("", ["path:"]);
if(!isset($opts["path"])){
exit(1);
}
$path = realpath($opts["path"]);
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $path => $f){
if(substr($path, -4) !== ".php"){
continue;
}
$oldTree = $tree = token_get_all(file_get_contents($path));
fastOptimize($tree);
if($tree !== $oldTree){
echo "Optimized $path\n";
file_put_contents($path, recreateTree($tree));
}
//var_dump($oldTree);
}
function fastOptimize(array &$tree){
$constantOptimize = [
"PHP_INT_MAX" => true,
"PHP_INT_SIZE" => true,
"PHP_EOL" => true,
"TRUE" => true,
"FALSE" => true,
"NULL" => true,
"ENDIANNESS" => true,
];
foreach($tree as $index => &$token){
if(is_array($token)){
if($token[0] === T_STRING and ($before = getBefore($tree, $index)) !== "\\"){
if(isset($constantOptimize[strtoupper($token[1])]) and $before !== "::" and $before !== "->"){
$token[1] = "\\" . $token[1]; //Constant fetch optimization
}elseif(function_exists($token[1]) and $before !== "::" and $before !== "->" and $before !== "function" and getAfter($tree, $index) === "("){
$token[1] = "\\" . $token[1]; //Function call optimization
}
}
}else{
}
}
}
function getAfter(array $tree, $current){
do{
$token = $tree[++$current];
if(is_array($token)){
if($token[0] === T_WHITESPACE or $token[0] === T_COMMENT or $token[0] === T_DOC_COMMENT){
continue;
}
return $token[1];
}else{
return $token;
}
}while(isset($tree[$current]));
return null;
}
function getBefore(array $tree, $current){
do{
$token = $tree[--$current];
if(is_array($token)){
if($token[0] === T_WHITESPACE or $token[0] === T_COMMENT or $token[0] === T_DOC_COMMENT){
continue;
}
return $token[1];
}else{
return $token;
}
}while(isset($tree[$current]));
return null;
}
function recreateTree($tree){
$output = "";
foreach($tree as $token){
if(is_array($token)){
$output .= $token[1];
}else{
$output .= $token;
}
}
return $output;
}