Passed
Push — master ( 695800...976f6b )
by Dev
01:48
created

LogsAnalyzer::record()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 3
nc 2
nop 2
crap 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 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): array
46
    {
47 3
        if ($this->checkFile($filename)
48 3
           || ($handle = fopen(('.gz' == substr($filename, -3) ? 'compress.zlib://' : '').$filename, 'r')) === false) {
49
            throw new \Exception('A problem occured with file `'.$filename.'`');
50
        }
51
52 3
        $logs = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $logs is dead and can be removed.
Loading history...
53 3
        $lineCounter = 1;
54 3
        while (!feof($handle)) {
55 3
            $line = fgets($handle);
56 3
            $line = $line ? $this->parser->parse($line) : null;
57 3
            $this->record($line, $lineCounter);
58 3
            ++$lineCounter;
59
        }
60 3
        fclose($handle);
61
62 3
        return $this->logs;
63
    }
64
65 3
    protected function record($line, $lineCounter)
66
    {
67 3
        if ($line && $this->filter($line)) {
68 3
            $this->logs[$lineCounter] = $line;
69
        }
70 3
    }
71
}
72