Completed
Push — master ( bcc5fe...59ad42 )
by Dev
01:59
created

LogsAnalyzer::__construct()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4.074

Importance

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