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

BaseMatcher::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace byrokrat\autogiro\Parser\Matcher;
6
7
use byrokrat\autogiro\Line;
8
use byrokrat\autogiro\Exception\InvalidContentException;
9
10
/**
11
 * Base implementation of the Matcher interface
12
 */
13
abstract class BaseMatcher implements Matcher
14
{
15
    /**
16
     * @var int Start matching from
17
     */
18
    private $startPos;
19
20
    /**
21
     * @var int Length to match
22
     */
23
    private $length;
24
25
    /**
26
     * Set match area
27
     *
28
     * Note that to make matcher definitions and the technical specifications of
29
     * autoirot appear as similar as possible the first character of a line is
30
     * regarded as being in position one (1).
31
     */
32 8
    public function __construct(int $startPos, int $length)
33
    {
34 8
        $this->startPos = $startPos;
35 8
        $this->length = $length;
36 8
    }
37
38
    /**
39
     * Get a description of the expected content
40
     */
41
    abstract protected function getDescription(): string;
42
43
    /**
44
     * Check if string is valid according to matching rules
45
     */
46
    abstract protected function isMatch(string $str): bool;
47
48
    /**
49
     * Match line and grab substring on success
50
     *
51
     * @throws InvalidContentException if line does not match
52
     */
53 8
    public function match(Line $line): string
54
    {
55 8
        $str = $line->substr($this->startPos - 1, $this->length);
56
57 8
        if (!$this->isMatch($str)) {
58 4
            throw new InvalidContentException(
59
                sprintf(
60 4
                    "Invalid content '%s' (expecting %s) starting at position %s",
61
                    $str,
62 4
                    $this->getDescription(),
63 4
                    $this->startPos - 1
64
                )
65
            );
66
        }
67
68 4
        return $str;
69
    }
70
}
71