Completed
Push — master ( 703546...76237a )
by Hannes
02:22
created

AmountVisitor   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
dl 0
loc 45
rs 10
c 0
b 0
f 0
wmc 6
lcom 1
cbo 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A beforeAmount() 0 29 5
1
<?php
2
/**
3
 * This file is part of byrokrat\autogiro.
4
 *
5
 * byrokrat\autogiro is free software: you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License as published
7
 * by the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * byrokrat\autogiro is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with byrokrat\autogiro. If not, see <http://www.gnu.org/licenses/>.
17
 *
18
 * Copyright 2016-19 Hannes Forsgård
19
 */
20
21
declare(strict_types = 1);
22
23
namespace byrokrat\autogiro\Visitor;
24
25
use byrokrat\autogiro\Tree\Node;
26
use byrokrat\autogiro\Tree\Obj;
27
use Money\Money;
28
use Money\MoneyParser;
29
30
/**
31
 * Create amount object under child 'Object'
32
 */
33
final class AmountVisitor extends Visitor
34
{
35
    use ErrorAwareTrait;
36
37
    /**
38
     * @var MoneyParser
39
     */
40
    private $moneyParser;
41
42
    public function __construct(ErrorObject $errorObj, MoneyParser $moneyParser)
43
    {
44
        $this->setErrorObject($errorObj);
45
        $this->moneyParser = $moneyParser;
46
    }
47
48
    public function beforeAmount(Node $node): void
49
    {
50
        if ($node->hasChild('Object')) {
51
            return;
52
        }
53
54
        $signalStr = (string)$node->getValueFrom('Text');
55
56
        if (trim($signalStr) == '') {
57
            return;
58
        }
59
60
        try {
61
            // due to charset issues unknown trailing signal chars are treated as 'å'
62
            if (!preg_match('/^[0-9åJKLMNOPQR]$/', mb_substr($signalStr, -1))) {
63
                $signalStr = '-' . mb_substr($signalStr, 0, -1) . '0';
64
            }
65
66
            $money = $this->moneyParser->parse($signalStr);
67
68
            $node->addChild(new Obj($node->getLineNr(), $money));
69
        } catch (\Exception $e) {
70
            $this->getErrorObject()->addError(
71
                "Invalid signaled amount %s on line %s",
72
                (string)$node->getValueFrom('Text'),
73
                (string)$node->getLineNr()
74
            );
75
        }
76
    }
77
}
78