Passed
Push — master ( b40bc2...29ef41 )
by Mr
07:40
created

MoneyService   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
c 1
b 0
f 0
dl 0
loc 43
ccs 0
cts 30
cp 0
rs 10
wmc 4

4 Methods

Rating   Name   Duplication   Size   Complexity  
A format() 0 4 1
A __construct() 0 11 1
A convert() 0 7 1
A parse() 0 4 1
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
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(MoneyInterface $money, string $currency): MoneyInterface
57
    {
58
        $converted = $this->converter->convert(
59
            new PhpMoney($money->getAmount(), new PhpCurrency($money->getCurrency())),
60
            new PhpCurrency($currency)
61
        );
62
        return $this->moneyType::fromNative($converted->getAmount().$converted->getCurrency());
63
    }
64
}
65