Completed
Push — master ( 0622b2...2b7c3d )
by Dev
12:57 queued 11:51
created

LogsAnalyzer::checkFile()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

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