Thursday, October 19, 2017

more quick and dirty php: finding matching tags

Just here for my future reference - did another "PHP as command line scripting tool to recursively go over directories", this one to get a rough idea of, in our Freemarket Template codebase, how many
<#macro fooBar blah blah>
macro definitions were orphans, and never called with a
<@foobar blah blah >
tag. (Freemarker is hella flexible in terms of how you build a macro name to call, though, so this is far from bullet proof...)

<?
$directory = "/Users/kisrael/cargurus/cg-main/cargurus-site-static/templates/";

$macroDefLocations = array();
$macroCallLocations = array();

#checkfile("inventorylisting/ocrFilterMacros.ftl");

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));
while($it->valid()) {
    $pathname = $it->getSubPathName();
    if (endsWith($pathname, ".ftl")) {
    checkfile($pathname);
    }
    $it->next();
}

function checkfile($pathname){
global $macroDefLocations, $macroCallLocations;
    lookForMatches($pathname,$macroDefLocations,"/\<\#macro.*?\>/s","/\<\#macro\s(\w*)\W/s");
    lookForMatches($pathname,$macroCallLocations,"/\<\@.*?\>/s","/\<\@(\w*)\W/s");
}

foreach($macroDefLocations as $definedMacro => $usages){
if(! array_key_exists($definedMacro, $macroCallLocations)){
$file = array_keys($macroDefLocations[$definedMacro])[0];
print "[".$definedMacro."]\t".$file."\n";
$orphanedMacrosInFile[$file]++;
$orphan++;
} else {
$calledMacrosInFile[$file]++;
$wellcalled++;
}
}
#print "$orphan orphans $wellcalled called\n";
#print "CALLED:\n";
#print_r($calledMacrosInFile);
#print "ORPHANED:\n";
#print_r($orphanedMacrosInFile);

foreach($orphanedMacrosInFile as $file => $countOrphans){
$countCalled = 0;
if(array_key_exists($file, $calledMacrosInFile)){
$countCalled = $calledMacrosInFile[$file];


$percentOrphans[$file] = (100.0 * ($countOrphans) / ($countCalled +$countOrphans ));
$orphanDesc[$file] = "$countOrphans orphans / ".($countCalled +$countOrphans)." defs";

}
arsort($percentOrphans);

$keys = array_keys($percentOrphans);


foreach($keys as $file){
print round($percentOrphans[$file],3)."\t".$orphanDesc[$file]."\t".$file."\n";;
}


function lookForMatches($pathname,&$results,$regexFind,$regexExtract){
global $directory;
$content = file_get_contents($directory.$pathname);
preg_match_all($regexFind,$content,$matches);
foreach ($matches[0] as $key => $tag){
preg_match($regexExtract,$tag,$finds);
$macro = $finds[1];
#print "vvv\n$tag\n^^^\n";
if (! array_key_exists($macro,$results)){
$results[$macro] = array();

if (! array_key_exists($pathname,$results[$macro])){
$results[$macro][$pathname] = 0;
}
$results[$macro][$pathname]++;
}
}

function endsWith($haystack, $needle) {
    return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== false);
}
?>

No comments:

Post a Comment