LogsAnalyzer::filter()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 7
ccs 3
cts 4
cp 0.75
rs 10
cc 2
nc 2
nop 1
crap 2.0625
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
        $lineCounter = 1;
53 3
        while (! feof($handle)) {
54 3
            $line = fgets($handle);
55 3
            $line = $line ? $this->parser->parse($line) : null;
56 3
            $this->record($line, $lineCounter);
57 3
            ++$lineCounter;
58
        }
59 3
        fclose($handle);
60
61 3
        return $this->logs;
62
    }
63
64 3
    protected function record($line, $lineCounter)
65
    {
66 3
        if ($line && $this->filter($line)) {
67 3
            $this->logs[$lineCounter] = $line;
68
        }
69 3
    }
70
}
71