SummaryVisitor::afterSummary()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 18
rs 9.8666
cc 3
nc 3
nop 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
use Money\Money;
28
29
final class SummaryVisitor extends Visitor
30
{
31
    use ErrorAwareTrait;
32
33
    /**
34
     * @var Money[]
35
     */
36
    private $summaries = [];
37
38
    public function beforeAutogiroFile(): void
39
    {
40
        $this->summaries = [];
41
    }
42
43
    public function afterRecord(Node $node): void
44
    {
45
        if ($amount = $node->getChild(Node::AMOUNT)->getObjectValue()) {
46
            $summary = $this->summaries[$node->getName()] ?? $amount->subtract($amount);
47
            $this->summaries[$node->getName()] = $summary->add($amount);
48
        }
49
    }
50
51
    public function afterSummary(Node $node): void
52
    {
53
        $expectedAmount = $node->getChild(Node::AMOUNT)->getObjectValue();
54
55
        if (!$expectedAmount) {
56
            return;
57
        }
58
59
        $currentAmount = $this->summaries[(string)$node->getValueFrom('Text')]
60
            ?? $expectedAmount->subtract($expectedAmount);
61
62
        if (!$expectedAmount->absolute()->equals($currentAmount->absolute())) {
63
            $this->getErrorObject()->addError(
64
                "Invalid %s node summary (found: %s, expected: %s) on line %s",
65
                (string)$node->getValueFrom('Text'),
66
                (string)$currentAmount->getAmount(),
67
                (string)$expectedAmount->getAmount(),
68
                (string)$node->getLineNr()
69
            );
70
        }
71
    }
72
}
73