Skip to content

Instantly share code, notes, and snippets.

@legierski
Created November 17, 2012 15:09
Show Gist options
  • Save legierski/4096650 to your computer and use it in GitHub Desktop.
Save legierski/4096650 to your computer and use it in GitHub Desktop.
Calculate how much indentation there is in your PHP project
<?
$spaces = calculate_spaces('folder-name');
echo 'Spaces and tabs used for indentation account for '.$spaces['percent'].'% of selected folder\'s files ('.$spaces['spaces'].' spaces, '.$spaces['total'].' total characters).';
function calculate_spaces($path) {
$spaces_counter = 0;
$total_counter = 0;
$paths = list_files_recursive($path);
foreach($paths as $path) {
if(is_allowed_type($path)) {
$lines = split_into_lines($path);
foreach($lines as $line) {
$spaces_counter += count_indentation_chars($line);
}
$total_counter += file_size($path);
}
}
return array(
'spaces' => $spaces_counter,
'total' => $total_counter,
'percent' => number_format(($spaces_counter/$total_counter)*100, 2)
);
}
function list_files_recursive($dir) {
$file_list = array();
$elements = scandir($dir);
foreach($elements as $element) {
if(!in_array($element, array('.', '..'))) {
if(is_dir($dir.'/'.$element)) {
$tmp = list_files_recursive($dir.'/'.$element);
$file_list = array_merge($file_list, $tmp);
}
else {
$file_list[] = $dir.'/'.$element;
}
}
}
return $file_list;
}
function is_allowed_type($filename) {
$allowed_types = array('php', 'htm', 'html');
$type = end(explode('.', $filename));
return in_array($type, $allowed_types);
}
function split_into_lines($path) {
$data = read_file($path);
if($data !== false) {
return preg_split('/\r\n|\r|\n/', $data);
}
else {
return false;
}
}
function read_file($path) {
if (!file_exists($path)) {
return false;
}
return file_get_contents($path);
}
function file_size($path) {
if (!file_exists($path)) {
return 0;
}
return filesize($path);
}
function count_indentation_chars($string) {
$length = 0;
$matches = array();
preg_match('/^[ \t]+/', $string, $matches);
foreach($matches as $match) {
$length += strlen($match);
}
return $length;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment