Completed
Push — master ( 59e0d1...2311d4 )
by Dev
15:01 queued 13:47
created

LogsAnalyzer   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 18
eloc 27
dl 0
loc 63
ccs 0
cts 31
cp 0
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 4
A filter() 0 7 2
A checkFile() 0 3 2
A setFilter() 0 3 1
A parse() 0 17 6
A record() 0 4 3
1
<?php
2
3
namespace PiedWeb\LogsAnalyzer;
4
5
class LogsAnalyzer
6
{
7
    protected $parser;
8
9
    protected $filter;
10
11
    protected $logs = [];
12
13
    public function __construct(string $type, ?string $domain = null)
14
    {
15
        $this->parser = new LogParser();
16
        $this->parser->setFormat(class_exists($type) ? $type::FORMAT : $type);
17
        if ($domain !== null) {
18
            $this->parser->setDomain($domain);
19
        }
20
        $this->parser->setType(class_exists($type) ? $type : LogLine::class);
21
    }
22
23
    /**
24
     * The function must return TRUE for line we want to keep / FALSE for line to ignore
25
     */
26
    public function setFilter($filter)
27
    {
28
        $this->filter = $filter;
29
    }
30
31
    protected function checkFile(string $filename): bool
32
    {
33
        return !file_exists($filename) || !is_readable($filename);
34
    }
35
36
    protected function filter($line)
37
    {
38
        if ($this->filter) {
39
            return call_user_func($this->filter, $line);
40
        }
41
42
        return true;
43
    }
44
45
    public function parse(string $filename): array
46
    {
47
        if ($this->checkFile($filename)
48
           || ($handle = fopen(('.gz' == substr($filename, -3) ? 'compress.zlib://' : '').$filename, 'r')) === false) {
49
            throw new \Exception('A problem occured with file `'.$filename.'`');
50
        }
51
52
        $lineCounter = 1;
53
        while (!feof($handle)) {
54
            $line = fgets($handle);
55
            $line = $line ? $this->parser->parse($line) : null;
56
            $this->record($line, $lineCounter);
57
            ++$lineCounter;
58
        }
59
        fclose($handle);
60
61
        return $this->logs;
62
    }
63
64
    protected function record($line, $lineCounter)
65
    {
66
        if ($line && $this->filter($line)) {
67
            $this->logs[$lineCounter] = $line;
68
        }
69
    }
70
}
71