- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 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
<?php
class CodeCounter {
const MULTILINE_COMMENT = 0x01;
private $dir = null;
private $ext = null;
public function __construct($dir = '.', $ext = '*') {
$this->dir = $dir;
if($ext == '*') {
$this->ext = "/.*/si";
} else {
$e = explode('|', $ext);
foreach($e as &$ext) {
$ext = trim($ext);
if($ext == '')
unset($ext);
}
$r = implode('|', $e);
$this->ext = "/.*\.({$r})$/si";
}
}
public function calculate() {
$lines = 0;
$args = func_get_args();
if(count($args) == 0)
$dir = $this->dir;
else
$dir = $args[0];
if(file_exists($dir) && is_dir($dir)) {
$list = scandir($dir);
foreach($list as $item) {
if($item == '.' || $item == '..')
continue;
$fullItem = realpath($dir . DIRECTORY_SEPARATOR . $item);
if(is_dir($fullItem)) {
$lines += $this->calculate($fullItem);
} else {
if(preg_match($this->ext, $item)) {
echo "Calculating lines in {$fullItem}: ";
$_lines = self::count($fullItem);
echo "{$_lines}\n";
$lines += $_lines;
}
}
}
}
return $lines;
}
private static function count($file) {
$lines = 0;
$d = null;
if(file_exists($file) && ($file = file($file))) {
foreach($file as $line) {
$line = trim($line);
if($line == '')
continue;
if( substr($line, 0, 2) == '//' || //single line comment
substr($line, 0, 1) == '#' || //single line comment
substr($line, 0, 2) == '<?' || //php open tag
substr($line, 0, 2) == '?>' //php close tags
)
continue;
if(($pos = strpos('/*', $line)) !== false) {
if($pos == 0) {
if(strpos('*/', $line, $pos) === false) {
$d = self::MULTILINE_COMMENT;
}
} else {
$lines++;
}
continue;
}
if($d == self::MULTILINE_COMMENT) {
if(strpos('*/', $line) !== false) {
$d = null;
}
continue;
}
$lines++;
}
}
return $lines;
}
}
$counter = new CodeCounter('./amapys', 'php|js');
$lines = $counter->calculate();
echo "\nTotal: {$lines} lines\n";