Parses out functions in a JavaScript file, and collects their dependencies
<?php
/**
* JavaScript Functional Dependency Parser
*
* DISCLAIMER:
* This script is based on some of the worst parsing methodologies ever (RegEx, blacklisting...)
* Do not use this script if you are expecting perfection
* This is merely a scraper with some additional processing to cleanup the output
*/
// Configure
define('FILENAME', 'myfile.js'); // The file to parse
$blacklist = [ // List of "functions" to hide
'if', 'click', 'val', 'log', 'show',
'hide', 'filter', 'prop', 'last', 'inArray',
'parseInt', 'each', 'parent', 'min', 'match',
'attr', 'gt', 'is', 'ceil', 'html',
'append', 'function', 'text', 'alert', 'find',
'slice', 'test', 'push', 'first', '^',
'toFixed', 'round', 'join', 'switch', 'prepend'
];
// Initialize
$file = fopen(FILENAME, 'r');
$functions = [];
while(($line = fgets($file)) !== false) {
// Find function definition
if(preg_match('@function (.+)\(@', $line, $matches)) {
// Store function name
$functions[$matches[1]] = [];
// Check for contained functions
// TODO: The search algorithm is terrible, sorry
$left = 1;
$right = 0;
while(($line = fgets($file)) !== false) {
// Count brackets
$left += substr_count($line, '{');
$right += substr_count($line, '}');
if(preg_match('@([A-z]+)\(@', $line, $matchesInner)) {
if(!in_array($matchesInner[1], $blacklist) && !in_array($matchesInner[1], $functions[$matches[1]])) {
$functions[$matches[1]][] = $matchesInner[1];
}
}
// End of function
if($left == $right) {break;}
}
}
}
fclose($file);
// Sort by number of sub-functions
uasort($functions, function($a, $b) {
return count($a) - count($b);
});
// Print
foreach($functions as $function => $depends) {
echo "$function\n";
sort($depends);
foreach($depends as $subfunction) {
echo "\t$subfunction\n";
}
echo "\n";
}
exit;