|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
/** |
|
3
|
|
|
* This file is part of the daikon-cqrs/money-interop project. |
|
4
|
|
|
* |
|
5
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
6
|
|
|
* file that was distributed with this source code. |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace Daikon\Money\Service; |
|
10
|
|
|
|
|
11
|
|
|
use Daikon\Interop\Assertion; |
|
12
|
|
|
use Daikon\Money\ValueObject\Money; |
|
13
|
|
|
use Daikon\Money\ValueObject\MoneyInterface; |
|
14
|
|
|
use Money\Converter; |
|
15
|
|
|
use Money\Currency as PhpCurrency; |
|
16
|
|
|
use Money\Money as PhpMoney; |
|
17
|
|
|
use Money\MoneyFormatter; |
|
18
|
|
|
use Money\MoneyParser; |
|
19
|
|
|
|
|
20
|
|
|
final class MoneyService implements MoneyServiceInterface |
|
21
|
|
|
{ |
|
22
|
|
|
private MoneyParser $parser; |
|
23
|
|
|
|
|
24
|
|
|
private Converter $converter; |
|
25
|
|
|
|
|
26
|
|
|
private MoneyFormatter $formatter; |
|
27
|
|
|
|
|
28
|
|
|
private string $moneyType; |
|
29
|
|
|
|
|
30
|
|
|
public function __construct( |
|
31
|
|
|
MoneyParser $parser, |
|
32
|
|
|
Converter $converter, |
|
33
|
|
|
MoneyFormatter $formatter, |
|
34
|
|
|
string $moneyType = null |
|
35
|
|
|
) { |
|
36
|
|
|
$this->parser = $parser; |
|
37
|
|
|
$this->converter = $converter; |
|
38
|
|
|
$this->formatter = $formatter; |
|
39
|
|
|
Assertion::implementsInterface($moneyType, MoneyInterface::class, 'Not a valid money implementation.'); |
|
40
|
|
|
$this->moneyType = $moneyType ?? Money::class; |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
public function parse(string $amount, string $currency = null): MoneyInterface |
|
44
|
|
|
{ |
|
45
|
|
|
$parsed = $this->parser->parse($amount, $currency); |
|
46
|
|
|
return $this->moneyType::fromNative($parsed->getAmount().$parsed->getCurrency()); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
public function format(MoneyInterface $money): string |
|
50
|
|
|
{ |
|
51
|
|
|
return $this->formatter->format( |
|
52
|
|
|
new PhpMoney($money->getAmount(), new PhpCurrency($money->getCurrency())) |
|
53
|
|
|
); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
public function convert( |
|
57
|
|
|
MoneyInterface $money, |
|
58
|
|
|
string $currency, |
|
59
|
|
|
int $roundingMode = MoneyInterface::ROUND_HALF_UP |
|
60
|
|
|
): MoneyInterface { |
|
61
|
|
|
if ($money->getCurrency() !== $currency) { |
|
62
|
|
|
$money = $this->converter->convert( |
|
63
|
|
|
new PhpMoney($money->getAmount(), new PhpCurrency($money->getCurrency())), |
|
64
|
|
|
new PhpCurrency($currency), |
|
65
|
|
|
$roundingMode |
|
66
|
|
|
); |
|
67
|
|
|
} |
|
68
|
|
|
return $this->moneyType::fromNative($money->getAmount().$money->getCurrency()); |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|