-
Notifications
You must be signed in to change notification settings - Fork 0
/
unusedSASS.php
110 lines (87 loc) · 2.68 KB
/
unusedSASS.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#!/usr/bin/php
<?php
/**
* Please adjust
*/
$PATH = "./";
$outputFileName = 'unusedSass.txt';
// Default pattern
$pattern = '/\$-?[_a-zA-Z0-9-]+[_a-zA-Z0-9-]\:/';
$replace = [':'];
$searchFor = 'SASS variables';
$searchIn = 'css';
if($argc > 0){
// Check for path
foreach($argv as $v){
$len = strlen($v);
if($len >= 3) {
if(substr( $v, 0, 3 ) === "-p="){
$PATH = substr( $v, 3, $len );
break;
}
}
}
}
/**
* SCRIPT START
*/
ini_set('max_execution_time', 0);
function getFilesRecursive($dir, $results = ['css'=> [], 'others'=>[]]){
$files = scandir($dir);
foreach($files as $key => $value){
$path = realpath($dir.DIRECTORY_SEPARATOR.$value);
if(!is_dir($path)) {
if(strpos($path, '.scss') || strpos($path, '.css')){
$results['css'][] = $path;
}
} else if($value !== "." && $value !== "..") {
$results = getFilesRecursive($path, $results);
}
}
return $results;
}
// Get list of all files
$listOfAllFiles = getFilesRecursive($PATH);
// Get all searched strings
$sassVars = [];
foreach($listOfAllFiles['css'] as $cssFile){
$content = file_get_contents($cssFile);
preg_match_all($pattern, $content, $listOfAllCssClassesInFile);
$sassVars = array_merge($sassVars, $listOfAllCssClassesInFile[0]);
}
// Get clean strings
foreach($sassVars as $key => $value){
$sassVars[$key] = str_replace($replace, '', $value);
}
// Backup
$sassVarsUncounted = $sassVars;
// Create list of variable usages
$sassVarUsages = [];
foreach($listOfAllFiles[$searchIn] as $file){
$fileContent = file_get_contents($file);
foreach($sassVarsUncounted as $var_key => $var_name){
$amount = substr_count($fileContent, $var_name);
if(isset($sassVarUsages[$var_name])){
$sassVarUsages[$var_name] += $amount;
}else{
$sassVarUsages[$var_name] = $amount;
}
}
}
foreach($sassVarUsages as $var_name => $var_count){
if($var_count > 1){
unset($sassVarUsages[$var_name]);
}
}
$unusedSassVars = $sassVarUsages;
// Unused CSS classes
$unusedSassVarssAsText = '';
foreach($unusedSassVars as $unusedSassVarName => $unusedSassVarValue){
$unusedSassVarssAsText .= $unusedSassVarName.PHP_EOL;
}
file_put_contents($outputFileName, $unusedSassVarssAsText);
echo "Amount S(CSS) files:".count($listOfAllFiles['css']).PHP_EOL;
echo "Amount other files:".count($listOfAllFiles['others']).PHP_EOL;
echo "Amount ".$searchFor.":".count($sassVars).PHP_EOL;
echo "Amount unused ".$searchFor.":".count($unusedSassVars).PHP_EOL;
echo $searchFor." written to: ".$outputFileName.PHP_EOL;