SignalMoneyFormatter::format()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 19
rs 9.9666
cc 4
nc 4
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\Money;
25
26
use byrokrat\autogiro\Exception\RuntimeException;
27
use Money\Money;
28
use Money\MoneyFormatter;
29
30
final class SignalMoneyFormatter implements MoneyFormatter
31
{
32
    private const SIGNALS = [
33
        '0' => 'å',
34
        '1' => 'J',
35
        '2' => 'K',
36
        '3' => 'L',
37
        '4' => 'M',
38
        '5' => 'N',
39
        '6' => 'O',
40
        '7' => 'P',
41
        '8' => 'Q',
42
        '9' => 'R',
43
    ];
44
45
    public function format(Money $money)
46
    {
47
        if ($money->getCurrency()->getCode() != 'SEK') {
48
            throw new RuntimeException('SignalMoneyFormatter can only work with SEK');
49
        }
50
51
        $amount = $money->getAmount();
52
53
        if ($money->isPositive()) {
54
            return $amount;
55
        }
56
57
        $lastChar = substr($amount, -1);
58
59
        if (isset(self::SIGNALS[$lastChar])) {
60
            return substr($amount, 1, -1) . self::SIGNALS[$lastChar];
61
        }
62
63
        throw new \LogicException("Unknown signal amount ending char: $lastChar");
64
    }
65
}
66