Completed
Push — master ( 310596...ecf895 )
by Hannes
02:21
created

RecordReader::addMatcher()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 2
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace byrokrat\autogiro\Parser;
6
7
use byrokrat\autogiro\Line;
8
use byrokrat\autogiro\Record\Record;
9
10
/**
11
 * Match and capture parts of a line into a Record
12
 */
13
class RecordReader
14
{
15
    /**
16
     * @var Matcher\Matcher
17
     */
18
    private $matchers = [];
19
20
    /**
21
     * @var callable Record builder
22
     */
23
    private $builder;
24
25
    /**
26
     * Inject matchers and builder
27
     *
28
     * The builder should take an array of values captured by registered
29
     * matchers and return a Record object.
30
     */
31 1
    public function __construct(array $matchers, callable $builder)
32
    {
33 1
        foreach ($matchers as $key => $matcher) {
34 1
            $this->addMatcher($key, $matcher);
35
        }
36 1
        $this->setBuilder($builder);
37 1
    }
38
39
    /**
40
     * Create Record from matched $line content
41
     */
42 1
    public function readRecord(Line $line): Record
43
    {
44 1
        $parts = [];
45
46 1
        foreach ($this->matchers as $key => $matcher) {
0 ignored issues
show
Bug introduced by
The expression $this->matchers of type object<byrokrat\autogiro\Parser\Matcher\Matcher> is not traversable.
Loading history...
47 1
            $parts[$key] = $matcher->match($line);
48
        }
49
50 1
        return ($this->builder)($parts);
51
    }
52
53
    /**
54
     * Add content matcher
55
     */
56 1
    protected function addMatcher(string $key, Matcher\Matcher $matcher)
57
    {
58 1
        $this->matchers[$key] = $matcher;
59 1
    }
60
61
    /**
62
     * Set record builder
63
     */
64 1
    protected function setBuilder(callable $builder)
65
    {
66 1
        $this->builder = $builder;
67 1
    }
68
}
69