It's not 100% accurate, as SLOC is *only* what I consider an actual line of code...it would be trivial to add a counter for comments and perform calculations such as comments/line ratios, etc...
I simply wanted something quick and dirty to give me an idea of how many lines I have removed from an existing project...
Use:
Line: 35 globr()
- first parameter is the directory you wish to traverse relative to the executing script
- second parameter is the filter list the example is obvious???
Problems:
It's slow on large projects. You will likely need to increase the time PHP is allowed to execute. It barely finished on my project which is just over 30,000 physical lines.
Code: Select all
<?php
//
// Borrowed from php.net/glob
function globr($sDir, $sPattern, $nFlags = NULL)
{
$sDir = escapeshellcmd($sDir);
// Get the list of all matching files currently in the
// directory.
$aFiles = glob("$sDir/$sPattern", $nFlags);
// Then get a list of all directories in this directory, and
// run ourselves on the resulting array. This is the
// recursion step, which will not execute if there are no
// directories.
foreach (glob("$sDir/*", GLOB_ONLYDIR) as $sSubDir)
{
$aSubFiles = globr($sSubDir, $sPattern, $nFlags);
$aFiles = array_merge($aFiles, $aSubFiles);
}
// The array we return contains the files we found, and the
// files all of our children found.
return $aFiles;
}
$sts = 0; // Statements
$con = 0; // Keywords
$lin = 0; // Actual physical lines
$siz = 0;
$dir = globr('webedit', '{*.php,*.inc}', GLOB_BRACE);
// Iterate files which match above glob()
for($h=0; $h<count($dir); $h++){
$src = file_get_contents($dir[$h]);
$arr = token_get_all($src);
$cnt = count($arr);
$siz += strlen($src);
// Physical line counter
for($i=0; $i<strlen($src); $i++){
if(ord($src[$i]) == 10) $lin++;
}
// Iterate tokens
for($i=0; $i<$cnt; $i++){
if($arr[$i] == ';') $sts++; // Increment statement counter
switch($arr[$i][1]){
case 'do':
case 'if':
case 'for':
case 'case':
case 'loop':
case 'while':
case 'elseif':
case 'switch':
case 'default':
case 'foreach':
$con++; // Increment construct counter
}
}
}
printf("Physical Files: %d<br>", count($dir));
printf("Physical Lines: %d<br>", $lin);
printf("Size: %d Bytes<br>", $siz);
printf("Statements: %d<br>", $sts);
printf("Constructs: %d<br>", $con);
printf("--------------------------<br>");
printf("<b>SLOC Total: %d</b>", $sts+$con);