forked from nemiah/phpFinTS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGetStatementOfAccount.php
More file actions
266 lines (235 loc) · 9.61 KB
/
GetStatementOfAccount.php
File metadata and controls
266 lines (235 loc) · 9.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
<?php
namespace Fhp\Action;
use Fhp\CAMT\CAMT;
use Fhp\Model\SEPAAccount;
use Fhp\Model\StatementOfAccount\StatementOfAccount;
use Fhp\MT940\Dialect\PostbankMT940;
use Fhp\MT940\Dialect\SpardaMT940;
use Fhp\MT940\MT940;
use Fhp\MT940\MT940Exception;
use Fhp\PaginateableAction;
use Fhp\Protocol\BPD;
use Fhp\Protocol\Message;
use Fhp\Protocol\UnexpectedResponseException;
use Fhp\Protocol\UPD;
use Fhp\Segment\Common\Kti;
use Fhp\Segment\Common\Kto;
use Fhp\Segment\Common\KtvV3;
use Fhp\Segment\HIRMS\Rueckmeldungscode;
use Fhp\Segment\KAZ\HIKAZ;
use Fhp\Segment\KAZ\HIKAZS;
use Fhp\Segment\KAZ\HKKAZv4;
use Fhp\Segment\KAZ\HKKAZv5;
use Fhp\Segment\KAZ\HKKAZv6;
use Fhp\Segment\KAZ\HKKAZv7;
use Fhp\UnsupportedException;
/**
* Retrieves statements for one specific account or for all accounts that the user has access to. A statement is a
* series of financial transactions that pertain to the account, grouped by day.
*/
class GetStatementOfAccount extends PaginateableAction
{
// Request (if you add a field here, update __serialize() and __unserialize() as well).
/** @var SEPAAccount */
private $account;
/** @var \DateTime */
private $from;
/** @var \DateTime */
private $to;
/** @var bool */
private $allAccounts;
/** @var bool */
private $includeUnbooked;
// Information from the BPD needed to interpret the response.
/** @var string */
private $bankName;
// Internal action for XML fallback
/** @var GetStatementOfAccountXML|null */
private $xmlAction;
// Response
/** @var string */
private $rawMT940 = '';
/** @var array */
protected $parsedMT940 = [];
/** @var StatementOfAccount */
private $statement;
/**
* @param SEPAAccount $account The account to get the statement for. This can be constructed based on information
* that the user entered, or it can be {@link SEPAAccount} instance retrieved from {@link getAccounts()}.
* @param \DateTime|null $from If set, only transactions after this date (inclusive) are returned.
* @param \DateTime|null $to If set, only transactions before this date (inclusive) are returned.
* @param bool $allAccounts If set to true, will return statements for all accounts of the user. You still need to
* pass one of the accounts into $account, though.
* @return GetStatementOfAccount A new action instance.
*/
public static function create(SEPAAccount $account, ?\DateTime $from = null, ?\DateTime $to = null, bool $allAccounts = false, bool $includeUnbooked = false): GetStatementOfAccount
{
if ($from !== null && $to !== null && $from > $to) {
throw new \InvalidArgumentException('From-date must be before to-date');
}
$result = new GetStatementOfAccount();
$result->account = $account;
$result->from = $from;
$result->to = $to;
$result->allAccounts = $allAccounts;
$result->includeUnbooked = $includeUnbooked;
return $result;
}
/**
* @deprecated Beginning from PHP7.4 __unserialize is used for new generated strings, then this method is only used for previously generated strings - remove after May 2023
*/
public function serialize(): string
{
return serialize($this->__serialize());
}
public function __serialize(): array
{
return [
parent::__serialize(),
$this->account, $this->from, $this->to, $this->allAccounts, $this->includeUnbooked,
$this->bankName,
];
}
/**
* @deprecated Beginning from PHP7.4 __unserialize is used for new generated strings, then this method is only used for previously generated strings - remove after May 2023
*
* @param string $serialized
* @return void
*/
public function unserialize($serialized)
{
self::__unserialize(unserialize($serialized));
}
public function __unserialize(array $serialized): void
{
list(
$parentSerialized,
$this->account, $this->from, $this->to, $this->allAccounts, $this->includeUnbooked,
$this->bankName,
) = $serialized;
is_array($parentSerialized) ?
parent::__unserialize($parentSerialized) :
parent::unserialize($parentSerialized);
}
/**
* @return string The raw MT940 data received from the server.
* @noinspection PhpUnused
*/
public function getRawMT940(): string
{
$this->ensureDone();
return $this->rawMT940;
}
/**
* @return array The parsed MT940 data.
*/
public function getParsedMT940(): array
{
$this->ensureDone();
return $this->parsedMT940;
}
public function getStatement(): StatementOfAccount
{
$this->ensureDone();
return $this->statement;
}
protected function createRequest(BPD $bpd, ?UPD $upd)
{
$this->bankName = $bpd->getBankName();
// Try to use MT940 format (HIKAZS) if supported
try {
/** @var HIKAZS $hikazs */
$hikazs = $bpd->requireLatestSupportedParameters('HIKAZS');
if ($this->allAccounts && !$hikazs->getParameter()->getAlleKontenErlaubt()) {
throw new \InvalidArgumentException('The bank do not permit the use of allAccounts=true');
}
switch ($hikazs->getVersion()) {
case 4:
return HKKAZv4::create(Kto::fromAccount($this->account), $this->from, $this->to);
case 5:
return HKKAZv5::create(KtvV3::fromAccount($this->account), $this->allAccounts, $this->from, $this->to);
case 6:
return HKKAZv6::create(KtvV3::fromAccount($this->account), $this->allAccounts, $this->from, $this->to);
case 7:
return HKKAZv7::create(Kti::fromAccount($this->account), $this->allAccounts, $this->from, $this->to);
default:
throw new UnsupportedException('Unsupported HKKAZ version: ' . $hikazs->getVersion());
}
} catch (UnexpectedResponseException|UnsupportedException $e) {
// MT940 format not supported, fall back to XML format (HICAZS)
$this->xmlAction = GetStatementOfAccountXML::create($this->account, $this->from, $this->to, null, $this->allAccounts);
return $this->xmlAction->createRequest($bpd, $upd);
}
}
public function processResponse(Message $response)
{
parent::processResponse($response);
// If we're using XML fallback, delegate to the XML action
if ($this->xmlAction !== null) {
$this->xmlAction->processResponse($response);
// Parse XML and convert to StatementOfAccount once all pages are received
if (!$this->hasMorePages()) {
$this->parseXml();
}
return;
}
// Banks send just 3010 and no HIKAZ in case there are no transactions.
$isUnavailable = $response->findRueckmeldung(Rueckmeldungscode::NICHT_VERFUEGBAR) !== null;
$responseHikaz = $response->findSegments(HIKAZ::class);
$numResponseSegments = count($responseHikaz);
if (!$isUnavailable && $numResponseSegments < count($this->getRequestSegmentNumbers())) {
throw new UnexpectedResponseException("Only got $numResponseSegments HIKAZ response segments!");
}
/** @var HIKAZ $hikaz */
foreach ($responseHikaz as $hikaz) {
$this->rawMT940 .= $hikaz->getGebuchteUmsaetze()->getData();
if ($this->includeUnbooked and $hikaz->getNichtGebuchteUmsaetze() !== null) {
$this->rawMT940 .= $hikaz->getNichtGebuchteUmsaetze()->getData();
}
}
// Note: Pagination boundaries may cut in the middle of the MT940 data, so it is not possible to parse a partial
// reponse before having received all pages.
if (!$this->hasMorePages()) {
$this->parseMt940();
}
}
private function parseMt940()
{
if (str_contains(strtolower($this->bankName), 'sparda')) {
$parser = new SpardaMT940();
} elseif (str_contains(strtolower($this->bankName), 'postbank')) {
$parser = new PostbankMT940();
} else {
$parser = new MT940();
}
try {
// Note: Some banks encode their MT 940 data as SWIFT/ISO-8859 like it should be according to the
// specification (e.g. DKB), others just send UTF-8 (e.g. Consorsbank), so we try to detect it here.
$rawMT940 = mb_detect_encoding($this->rawMT940, 'UTF-8', true) === false
? mb_convert_encoding($this->rawMT940, 'UTF-8', 'ISO-8859-1') : $this->rawMT940;
$this->parsedMT940 = $parser->parse($rawMT940);
$this->statement = StatementOfAccount::fromMT940Array($this->parsedMT940);
} catch (MT940Exception $e) {
throw new \InvalidArgumentException('Invalid MT940 data', 0, $e);
}
}
private function parseXml()
{
if ($this->xmlAction === null) {
throw new \RuntimeException('XML action not initialized');
}
$xmlStrings = $this->xmlAction->getBookedXML();
if (empty($xmlStrings)) {
// No transactions available
$this->statement = new StatementOfAccount();
return;
}
try {
$parser = new CAMT();
$parsedCAMT = $parser->parse($xmlStrings);
$this->statement = StatementOfAccount::fromCAMTArray($parsedCAMT);
} catch (\Exception $e) {
throw new \InvalidArgumentException('Invalid CAMT XML data', 0, $e);
}
}
}