|
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
|
|
|
|