AbstractLineParser::getPattern()
last analyzed

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 1
ccs 0
cts 0
cp 0
c 0
b 0
f 0
nc 1
1
<?php
2
3
/*
4
 * (c) Mantas Varatiejus <[email protected]>
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
namespace MVar\LogParser;
11
12
use MVar\LogParser\Exception\MatchException;
13
use MVar\LogParser\Exception\ParserException;
14
15
/**
16
 * Abstract line parser.
17
 */
18
abstract class AbstractLineParser implements LineParserInterface
19
{
20
    /**
21
     * {@inheritdoc}
22
     */
23 6
    public function parseLine($line)
24
    {
25 6
        if (!is_string($line)) {
26 1
            throw new ParserException('Parser argument must be a string.');
27
        }
28
29 5
        $match = @preg_match($this->getPattern(), $line, $matches);
30
31 5
        if ($match === false) {
32 1
            $error = error_get_last();
33 1
            throw new ParserException("Matcher failure. Please check if given pattern is valid. ({$error["message"]})");
34
        }
35
36 4
        if (!$match) {
37 1
            throw new MatchException('Given line does not match predefined pattern.');
38
        }
39
40 3
        return $this->prepareParsedData($matches);
41
    }
42
43
    /**
44
     * Prepare parsed data (matches) for end user.
45
     *
46
     * @param array $matches
47
     *
48
     * @return array
49
     */
50 2
    protected function prepareParsedData(array $matches)
51
    {
52
        // Remove indexed values
53 2
        $filtered = array_filter(array_keys($matches), 'is_string');
54 2
        $result = array_intersect_key($matches, array_flip($filtered));
55 2
        $result = array_filter($result);
56
57 2
        return $result;
58
    }
59
60
    /**
61
     * Returns pattern of log line.
62
     *
63
     * @return string
64
     */
65
    abstract protected function getPattern();
66
}
67