forked from peoplepath/workshop-php
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnew.php
More file actions
102 lines (85 loc) · 2.4 KB
/
new.php
File metadata and controls
102 lines (85 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
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
94
95
96
97
98
99
100
101
102
<?php
// implementing classes apply a filter to a string
interface Filter {
function filter(string $str): string;
}
abstract class CascadeFilter implements Filter {
private $_previousFilter = null;
function __construct(?Filter $filter) {
$this->_previousFilter = $filter;
}
function filter(string $str): string {
if ($this->_previousFilter) {
return $this->_previousFilter->filter($str);
} else {
return $str;
}
}
}
class IsNotDebug extends CascadeFilter {
function filter(string $str): string {
$str = parent::filter($str);
return $str == 'debug' ? '' : $str;
}
}
class ExtractLogLevel extends CascadeFilter {
const PATTERN = '/test\.(\w+)/';
function filter(string $str): string {
$str = parent::filter($str);
if (preg_match(self::PATTERN, $str, $matches)) {
return strtolower($matches[1]);
} else {
return '';
}
}
}
class FileRowReader extends FilterIterator {
private $_filter = null;
function __construct(string $filename, Filter $filter) {
$this->_filter = $filter;
// parent is a generator
parent::__construct(
(function($filename){
$f = fopen($filename, 'r');
try {
while ($row = fgets($f)) {
yield $row;
}
} finally {
fclose($f);
}
})($filename)
);
}
public function current() {
return $this->_filter->filter($this->getInnerIterator()->current());
}
public function accept() {
if ($this->current() == '') {
return false;
}
return true;
}
}
// read and parse file
$filter = new IsNotDebug(new ExtractLogLevel(null));
$fileReader = new FileRowReader($argv[1], $filter);
// build stats
$stats = new class($fileReader) extends ArrayIterator {
function __construct(Iterable $iterator) {
$stats = array();
foreach ($iterator as $level) {
if (array_key_exists($level, $stats)) {
$stats[$level]++;
} else {
$stats[$level] = 1;
}
}
arsort($stats);
parent::__construct($stats);
}
};
// show stats
foreach ($stats as $level => $count) {
echo "$level: $count" . PHP_EOL;
}