Passed
Push — master ( 4c872c...6bb6d3 )
by Mr
02:02
created

MoneyValidator::validate()   A

Complexity

Conditions 5
Paths 10

Size

Total Lines 33
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 20
c 1
b 0
f 0
nc 10
nop 1
dl 0
loc 33
ccs 0
cts 28
cp 0
crap 30
rs 9.2888
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\Validator;
10
11
use Daikon\Interop\Assertion;
12
use Daikon\Interop\InvalidArgumentException;
13
use Daikon\Money\Service\MoneyService;
14
use Daikon\Money\ValueObject\MoneyInterface;
15
use Daikon\Validize\Validator\Validator;
16
use Money\Exception\ParserException;
17
18
final class MoneyValidator extends Validator
19
{
20
    private MoneyService $moneyService;
21
22
    public function __construct(MoneyService $moneyService)
23
    {
24
        $this->moneyService = $moneyService;
25
    }
26
27
    /** @param mixed $input */
28
    protected function validate($input): MoneyInterface
29
    {
30
        Assertion::string($input, 'Must be a string.');
31
32
        $settings = $this->getSettings();
33
        $convert = $settings['convert'] ?? false;
34
        $min = $settings['min'] ?? false;
35
        $max = $settings['max'] ?? false;
36
37
        try {
38
            $money = $this->moneyService->parse($input);
39
            if ($convert) {
40
                $money = $this->moneyService->convert($money, $convert);
41
            }
42
        } catch (ParserException $error) {
43
            throw new InvalidArgumentException('Invalid amount.');
44
        }
45
46
        if ($min !== false) {
47
            Assertion::true(
48
                $money->isGreaterThanOrEqual($this->moneyService->parse($min)),
49
                "Amount must be at least $min."
50
            );
51
        }
52
53
        if ($max !== false) {
54
            Assertion::true(
55
                $money->isLessThanOrEqual($this->moneyService->parse($max)),
56
                "Amount must be at most $max."
57
            );
58
        }
59
60
        return $money;
61
    }
62
}
63