summaryrefslogtreecommitdiffstats
path: root/library/Icinga/Protocol/File/FileIterator.php
blob: 64b66008c49a7d83e02006ee379c1b0d3d327bfd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
/* Icinga Web 2 | (c) 2014 Icinga Development Team | GPLv2+ */

namespace Icinga\Protocol\File;

use Icinga\Util\EnumeratingFilterIterator;
use Icinga\Util\File;

/**
 * Class FileIterator
 *
 * Iterate over a file, yielding only fields of non-empty lines which match a PCRE expression
 */
class FileIterator extends EnumeratingFilterIterator
{
    /**
     * A PCRE string with the fields to extract from the file's lines as named subpatterns
     *
     * @var string
     */
    protected $fields;

    /**
     * An associative array of the current line's fields ($field => $value)
     *
     * @var array
     */
    protected $currentData;

    public function __construct($filename, $fields)
    {
        $this->fields = $fields;
        $f = new File($filename);
        $f->setFlags(
            File::DROP_NEW_LINE |
            File::READ_AHEAD |
            File::SKIP_EMPTY
        );
        parent::__construct($f);
    }

    /**
     * Return the current data
     *
     * @return array
     */
    public function current(): array
    {
        return $this->currentData;
    }

    /**
     * Accept lines matching the given PCRE pattern
     *
     * @return bool
     *
     * @throws FileReaderException  If PHP failed parsing the PCRE pattern
     */
    public function accept(): bool
    {
        $data = array();
        $matched = preg_match(
            $this->fields,
            $this->getInnerIterator()->current(),
            $data
        );

        if ($matched === false) {
            throw new FileReaderException('Failed parsing regular expression!');
        } elseif ($matched === 1) {
            foreach ($data as $key => $value) {
                if (is_int($key)) {
                    unset($data[$key]);
                }
            }
            $this->currentData = $data;
            return true;
        }
        return false;
    }
}