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\MoneyParser; |
29
|
|
|
|
30
|
|
|
final class SignalMoneyParser implements MoneyParser |
31
|
|
|
{ |
32
|
|
|
private const SIGNALS = [ |
33
|
|
|
'å' => '0', |
34
|
|
|
'J' => '1', |
35
|
|
|
'K' => '2', |
36
|
|
|
'L' => '3', |
37
|
|
|
'M' => '4', |
38
|
|
|
'N' => '5', |
39
|
|
|
'O' => '6', |
40
|
|
|
'P' => '7', |
41
|
|
|
'Q' => '8', |
42
|
|
|
'R' => '9', |
43
|
|
|
]; |
44
|
|
|
|
45
|
|
|
public function parse($money, $forceCurrency = null) |
46
|
|
|
{ |
47
|
|
|
if (!is_string($money)) { |
48
|
|
|
throw new \InvalidArgumentException('Money must be a string'); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
if (empty($money)) { |
52
|
|
|
throw new RuntimeException('Money must not be empty'); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
$money = ltrim($money, '0'); |
56
|
|
|
|
57
|
|
|
if (empty($money)) { |
58
|
|
|
$money = '0'; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
// due to charset issues unknown trailing signal chars are treated as 'å' |
62
|
|
|
if (!preg_match('/^[0-9åJKLMNOPQR]$/', mb_substr($money, -1))) { |
63
|
|
|
$money = mb_substr($money, 0, -1) . 'å'; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
$lastChar = mb_substr($money, -1); |
67
|
|
|
|
68
|
|
|
if (isset(self::SIGNALS[$lastChar])) { |
69
|
|
|
$money = sprintf( |
70
|
|
|
'-%s%s', |
71
|
|
|
mb_substr($money, 0, mb_strlen($money) - 1), |
72
|
|
|
self::SIGNALS[$lastChar] |
73
|
|
|
); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
if (!preg_match('/^\-?[0-9]+$/', $money)) { |
77
|
|
|
throw new RuntimeException('Money is not a valid singal string'); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
return Money::SEK($money); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|