Completed
Push — master ( 5d18c7...cabcf3 )
by Hannes
16s queued 13s
created

AccountFactory::whitelistFormats()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 4
nc 3
nop 1
crap 3
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace byrokrat\banking;
6
7
use byrokrat\banking\Format\FormatContainer;
8
use byrokrat\banking\Format\FormatFactory;
9
use byrokrat\banking\Rewriter\RewriterContainer;
10
use byrokrat\banking\Rewriter\RewriterFactory;
11
use byrokrat\banking\Exception\InvalidAccountNumberException;
12
13
/**
14
 * Account number factory for accounts using clearing numbers
15
 */
16
class AccountFactory implements AccountFactoryInterface
17
{
18
    /**
19
     * @var AccountFactoryInterface
20
     */
21
    private $decoratedFactory;
22
23
    /**
24
     * @var RewriterContainer
25
     */
26
    private $rewriters;
27
28
    /**
29
     * @var FormatContainer
30
     */
31
    private $formats;
32
33
    /**
34
     * @param AccountFactoryInterface $decorated Decorated account factory
35
     * @param RewriterContainer       $rewriters Rewriters used if parsed the raw account number fails
36
     * @param FormatContainer         $formats   Possible formats used when parsing account
37
     */
38 4
    public function __construct(
39
        AccountFactoryInterface $decorated = null,
40
        RewriterContainer $rewriters = null,
41
        FormatContainer $formats = null
42
    ) {
43 4
        $this->decoratedFactory = $decorated ?: new PermissiveFactory;
44 4
        $this->rewriters = $rewriters ?: (new RewriterFactory)->createRewriters();
45 4
        $this->formats = $formats ?: (new FormatFactory)->createFormats();
46 4
    }
47
48 144
    public function createAccount(string $number): AccountNumber
49
    {
50 144
        $account = $this->decoratedFactory->createAccount($number);
51
52 144
        $format = $this->formats->getFormatFromClearing($account);
53
54 144
        $result = $format->validate($account);
55
56 144
        if ($result->isValid()) {
57 88
            return new BankAccount($format->getBankName(), $account);
58
        }
59
60 139
        foreach ($this->rewriters as $rewriter) {
61 138
            $rewrittenAccount = $rewriter->rewrite($account);
62
63 138
            $rewrittenFormat = $this->formats->getFormatFromClearing($rewrittenAccount);
64
65 138
            if ($rewrittenFormat->validate($rewrittenAccount)->isValid()) {
66 138
                return new BankAccount($rewrittenFormat->getBankName(), $rewrittenAccount);
67
            }
68
        }
69
70 56
        throw new InvalidAccountNumberException(
71 56
            "Unable to parse account $number using format {$format->getBankName()}:\n{$result->getMessage()}"
72
        );
73
    }
74
}
75