CountingVisitor   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 17
c 1
b 0
f 0
dl 0
loc 48
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A increment() 0 3 1
A beforeCount() 0 12 2
A beforeAutogiroFile() 0 3 1
A beforeSection() 0 3 1
A getCount() 0 3 1
A beforeRecord() 0 3 1
1
<?php
2
3
/**
4
 * This file is part of byrokrat\autogiro.
5
 *
6
 * byrokrat\autogiro is free software: you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License as published
8
 * by the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * byrokrat\autogiro is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with byrokrat\autogiro. If not, see <http://www.gnu.org/licenses/>.
18
 *
19
 * Copyright 2016-21 Hannes Forsgård
20
 */
21
22
declare(strict_types=1);
23
24
namespace byrokrat\autogiro\Visitor;
25
26
use byrokrat\autogiro\Tree\Node;
27
28
final class CountingVisitor extends Visitor
29
{
30
    use ErrorAwareTrait;
31
32
    /**
33
     * @var int[]
34
     */
35
    private $counts = [];
36
37
    public function beforeAutogiroFile(): void
38
    {
39
        $this->counts = [];
40
    }
41
42
    public function beforeSection(Node $node): void
43
    {
44
        $this->increment($node->getName());
45
    }
46
47
    public function beforeRecord(Node $node): void
48
    {
49
        $this->increment($node->getName());
50
    }
51
52
    public function beforeCount(Node $node): void
53
    {
54
        $expectedCount = (int)$node->getValueFrom(Node::NUMBER);
55
        $currentCount = $this->getCount((string)$node->getValueFrom('Text'));
56
57
        if ($expectedCount != $currentCount) {
58
            $this->getErrorObject()->addError(
59
                "Invalid nr of %s nodes (found: %s, expected: %s) on line %s",
60
                (string)$node->getValueFrom('Text'),
61
                (string)$currentCount,
62
                (string)$expectedCount,
63
                (string)$node->getLineNr()
64
            );
65
        }
66
    }
67
68
    private function getCount(string $nodeName): int
69
    {
70
        return $this->counts[$nodeName] ?? 0;
71
    }
72
73
    private function increment(string $nodeName): void
74
    {
75
        $this->counts[$nodeName] = $this->getCount($nodeName) + 1;
76
    }
77
}
78