Completed
Push — master ( ecf895...d8752e )
by Hannes
03:16
created

RecordReader::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

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