-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathEngine.php
More file actions
699 lines (619 loc) · 18.5 KB
/
Engine.php
File metadata and controls
699 lines (619 loc) · 18.5 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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
<?php
namespace Kingsquare\Parser\Banking\Mt940;
use Kingsquare\Banking\Statement;
use Kingsquare\Banking\Transaction;
use Kingsquare\Parser\Banking\Mt940;
/**
* @author Kingsquare (source@kingsquare.nl)
* @license http://opensource.org/licenses/MIT MIT
*/
abstract class Engine
{
private $rawData = '';
protected $currentStatementData = '';
protected $currentTransactionData = '';
public $debug = false;
protected static $registeredEngines = [
100 => Engine\Abn::class,
200 => Engine\Ing::class,
300 => Engine\Rabo::class,
400 => Engine\Spk::class,
500 => Engine\Triodos::class,
600 => Engine\Knab::class,
700 => Engine\Hsbc::class,
800 => Engine\Bunq::class,
900 => Engine\Penta::class,
1000 => Engine\Asn::class,
1100 => Engine\Kbs::class,
1200 => Engine\Zetb::class,
1300 => Engine\Kontist::class,
];
/**
* reads the firstline of the string to guess which engine to use for parsing.
*
* @param string $string
*
* @return Engine
*/
public static function __getInstance($string)
{
$engine = self::detectBank($string);
$engine->loadString($string);
return $engine;
}
/**
* Register a new Engine.
*
* @param string $engineClass Class name of Engine to be registered
* @param int $priority
*/
public static function registerEngine($engineClass, $priority)
{
if (!is_int($priority)) {
trigger_error('Priority must be integer', E_USER_WARNING);
return;
}
if (array_key_exists($priority, self::$registeredEngines)) {
trigger_error('Priority already taken', E_USER_WARNING);
return;
}
if (!class_exists($engineClass)) {
trigger_error('Engine does not exist', E_USER_WARNING);
return;
}
self::$registeredEngines[$priority] = $engineClass;
}
/**
* Unregisters all Engines.
*/
public static function resetEngines()
{
self::$registeredEngines = [];
}
/**
* Checks whether the Engine is applicable for the given string.
*
* @param string $string
*
* @return bool
*/
public static function isApplicable($string)
{
return true;
}
/**
* @param string $string
*
* @return Engine
*/
private static function detectBank($string)
{
ksort(self::$registeredEngines, SORT_NUMERIC);
foreach (self::$registeredEngines as $engineClass) {
if ($engineClass::isApplicable($string)) {
return new $engineClass();
}
}
return new Engine\Unknown();
}
/**
* loads the $string into _rawData
* this could be used to move it into handling of streams in the future.
*
* @param string $string
*/
public function loadString($string)
{
$this->rawData = trim($string);
}
/**
* actual parsing of the data.
*
* @return Statement[]
*/
public function parse()
{
$results = [];
foreach ($this->parseStatementData() as $this->currentStatementData) {
$statement = new Statement();
if ($this->debug) {
$statement->rawData = $this->currentStatementData;
}
$statement->setBank($this->parseStatementBank());
$statement->setAccount($this->parseStatementAccount());
$statement->setBankCode($this->parseBankCode());
$statement->setAccountNumber($this->parseAccountNumber());
$statement->setStartPrice($this->parseStatementStartPrice());
$statement->setEndPrice($this->parseStatementEndPrice());
$statement->setStartTimestamp($this->parseStatementStartTimestamp());
$statement->setEndTimestamp($this->parseStatementEndTimestamp());
$statement->setNumber($this->parseStatementNumber());
$statement->setCurrency($this->parseStatementCurrency());
foreach ($this->parseTransactionData() as $this->currentTransactionData) {
$transaction = new Transaction();
if ($this->debug) {
$transaction->rawData = $this->currentTransactionData;
}
$transaction->setAccount($this->parseTransactionAccount());
$transaction->setAccountName($this->parseTransactionAccountName());
$transaction->setPrice($this->parseTransactionPrice());
$transaction->setDebitCredit($this->parseTransactionDebitCredit());
$transaction->setCancellation($this->parseTransactionCancellation());
$transaction->setDescription($this->parseTransactionDescription());
$transaction->setValueTimestamp($this->parseTransactionValueTimestamp());
$transaction->setEntryTimestamp($this->parseTransactionEntryTimestamp());
$transaction->setTransactionCode($this->parseTransactionCode());
$transaction->setFingerprint($this->calculateTransactionFingerprint());
$statement->addTransaction($transaction);
}
$results[] = $statement;
}
return $results;
}
/**
* split the rawdata up into statementdata chunks.
*
* @return array
*/
protected function parseStatementData()
{
$results = preg_split(
'/(^:20:|^-X{,3}$|\Z)/m',
$this->getRawData(),
-1,
PREG_SPLIT_NO_EMPTY
);
array_shift($results); // remove the header
return $results;
}
/**
* split the statement up into transaction chunks.
*
* @return array
*/
protected function parseTransactionData()
{
$results = [];
preg_match_all('/^:61:(.*?)(?=^:61:|^-X{,3}$|\Z)/sm', $this->getCurrentStatementData(), $results);
return !empty($results[0]) ? $results[0] : [];
}
/**
* return the actual raw data string.
*
* @return string _rawData
*/
public function getRawData()
{
return $this->rawData;
}
/**
* return the actual raw data string.
*
* @return string currentStatementData
*/
public function getCurrentStatementData()
{
return $this->currentStatementData;
}
/**
* return the actual raw data string.
*
* @return string currentTransactionData
*/
public function getCurrentTransactionData()
{
return $this->currentTransactionData;
}
// statement parsers, these work with currentStatementData
/**
* return the actual raw data string.
*
* @return string bank
*/
protected function parseStatementBank()
{
return '';
}
/**
* uses field 25 to gather accoutnumber.
*
* @return string accountnumber
*/
protected function parseStatementAccount()
{
$results = [];
if (preg_match('/:25:([\d\.]+)*/', $this->getCurrentStatementData(), $results)
&& !empty($results[1])
) {
return $this->sanitizeAccount($results[1]);
}
// SEPA / IBAN
if (preg_match('/:25:([A-Z0-9]{8}[\d\.]+)*/', $this->getCurrentStatementData(), $results)
&& !empty($results[1])
) {
return $this->sanitizeAccount($results[1]);
}
return '';
}
protected function parseBankCode()
{
$results = [];
if (preg_match('/:25:([A-Z0-9]{8})\/([\d\.]+)*/', $this->getCurrentStatementData(), $results)
&& !empty($results[1])
) {
return $results[1];
}
return '';
}
protected function parseAccountNumber()
{
$results = [];
if (preg_match('/:25:([A-Z0-9]*)\/([\d\.]+)*/', $this->getCurrentStatementData(), $results)
&& !empty($results[2])
) {
return ltrim($results[2], '0');
}
return '';
}
/**
* uses field 60F to gather starting amount.
*
* @return float price
*/
protected function parseStatementStartPrice()
{
return $this->parseStatementPrice('60F');
}
/**
* uses the 62F field to return end price of the statement.
*
* @return float price
*/
protected function parseStatementEndPrice()
{
return $this->parseStatementPrice('62F');
}
/**
* The actual pricing parser for statements.
*
* @param string $key
*
* @return float|string
*/
protected function parseStatementPrice($key)
{
$results = [];
if (preg_match('/:' . $key . ':([CD])?.*[A-Z]{3}([\d,\.]+)*/', $this->getCurrentStatementData(), $results)
&& !empty($results[2])
) {
$sanitizedPrice = $this->sanitizePrice($results[2]);
return (!empty($results[1]) && $results[1] === 'D') ? -$sanitizedPrice : $sanitizedPrice;
}
return '';
}
/**
* The currency initials parser for statements.
* @param string $key
* @return string currency initials
*/
protected function parseStatementCurrency($key = '60[FM]')
{
$results = [];
if (preg_match('/:' . $key . ':[CD]?.*([A-Z]{3})([\d,\.]+)*/', $this->getCurrentStatementData(), $results)) {
return $results[1];
}
return '';
}
/**
* uses the 60F field to determine the date of the statement.
*
* @deprecated will be removed in the next major release and replaced by startTimestamp / endTimestamps
*
* @return int timestamp
*/
protected function parseStatementTimestamp()
{
trigger_error('Deprecated in favor of splitting the start and end timestamps for a statement. ' .
'Please use parseStatementStartTimestamp($format) or parseStatementEndTimestamp($format) instead. ' .
'parseStatementTimestamp is now parseStatementStartTimestamp', E_USER_DEPRECATED);
return $this->parseStatementStartTimestamp();
}
/**
* uses the 60F field to determine the date of the statement.
*
* @return int timestamp
*/
protected function parseStatementStartTimestamp()
{
return $this->parseTimestampFromStatement('60F');
}
/**
* uses the 62F field to determine the date of the statement.
*
* @return int timestamp
*/
protected function parseStatementEndTimestamp()
{
return $this->parseTimestampFromStatement('62F');
}
protected function parseTimestampFromStatement($key)
{
$results = [];
if (preg_match('/:' . $key . ':[C|D](\d{6})*/', $this->getCurrentStatementData(), $results)
&& !empty($results[1])
) {
return $this->sanitizeTimestamp($results[1]);
}
return 0;
}
/**
* uses the 28C field to determine the statement number.
*
* @return string
*/
protected function parseStatementNumber()
{
$results = [];
if (preg_match('/:28C?:(.*)/', $this->getCurrentStatementData(), $results)
&& !empty($results[1])
) {
return trim($results[1]);
}
return '';
}
// transaction parsers, these work with getCurrentTransactionData
/**
* uses the 86 field to determine account number of the transaction.
*
* @return string
*/
protected function parseTransactionAccount()
{
$results = [];
if (preg_match('/^:86: ?([\d\.]+)\s/m', $this->getCurrentTransactionData(), $results)
&& !empty($results[1])
) {
return $this->sanitizeAccount($results[1]);
}
return '';
}
/**
* uses the 86 field to determine accountname of the transaction.
*
* @return string
*/
protected function parseTransactionAccountName()
{
$results = [];
if (preg_match('/:86: ?[\d\.]+ (.+)/', $this->getCurrentTransactionData(), $results)
&& !empty($results[1])
) {
return $this->sanitizeAccountName($results[1]);
}
return '';
}
/**
* uses the 61 field to determine amount/value of the transaction.
*
* @return float
*/
protected function parseTransactionPrice()
{
$results = [];
if (preg_match('/^:61:.*?[CD]([\d,\.]+)N/i', $this->getCurrentTransactionData(), $results)
&& !empty($results[1])
) {
return $this->sanitizePrice($results[1]);
}
return 0;
}
/**
* uses the 61 field to determine debit or credit of the transaction.
*
* @return string
*/
protected function parseTransactionDebitCredit()
{
$results = [];
if (preg_match('/^:61:\d+([CD])\d+/', $this->getCurrentTransactionData(), $results)
&& !empty($results[1])
) {
return $this->sanitizeDebitCredit($results[1]);
}
return '';
}
/**
* Parses the Cancellation flag of a Transaction
*
* @return boolean
*/
protected function parseTransactionCancellation()
{
return false;
}
/**
* uses the 86 field to determine retrieve the full description of the transaction.
*
* @return string
*/
protected function parseTransactionDescription()
{
$results = [];
if (preg_match_all('/[\n]:86:(.*?)(?=\n(:6([12]))|$)/s', $this->getCurrentTransactionData(), $results)
&& !empty($results[1])
) {
return $this->sanitizeDescription(implode(PHP_EOL, $results[1]));
}
return '';
}
/**
* uses the 61 field to determine the entry timestamp.
*
* @return int
*/
protected function parseTransactionEntryTimestamp()
{
$results = [];
if (preg_match('/^:61:(\d{2})((\d{2})\d{2})((\d{2})\d{2})[C|D]/', $this->getCurrentTransactionData(), $results)
&& !empty($results[1])
) {
list(, $valueDateY, $valueDateMD, $valueDateM, $entryDateMD, $entryDateM) = $results;
$entryDate = $valueDateY . $entryDateMD;
if ($valueDateMD !== $entryDateMD && $valueDateM > $entryDateM) {
$entryDate = ($valueDateY + 1) . $entryDateMD;
}
return $this->sanitizeTimestamp($entryDate, 'ymd');
}
return $this->parseTransactionValuta('61');
}
/**
* uses the 61 field to determine the value timestamp.
*
* @return int
*/
protected function parseTransactionValueTimestamp()
{
return $this->parseTransactionValuta('61');
}
/**
* This does the actual parsing of the transaction timestamp for given $key.
*
* @param string $key
* @return int
*/
protected function parseTransactionValuta($key)
{
$results = [];
if (preg_match('/^:' . $key . ':(\d{6})/', $this->getCurrentTransactionData(), $results)
&& !empty($results[1])
) {
return $this->sanitizeTimestamp($results[1]);
}
return 0;
}
/**
* uses the 61 field to get the bank specific transaction code.
*
* @return string
*/
protected function parseTransactionCode()
{
$results = [];
if (preg_match('/^:61:.*?N(.{3}).*/', $this->getCurrentTransactionData(), $results)
&& !empty($results[1])
) {
return trim($results[1]);
}
return '';
}
protected function getField(string $code)
{
$results = [];
if (preg_match("/:$code:(.*?):\d\d.?:/s", $this->getCurrentTransactionData(), $results)
&& !empty($results[1])
) {
return trim($results[1]);
}
if (preg_match("/:$code:(.*)/s", $this->getCurrentTransactionData(), $results)
&& !empty($results[1])
) {
return trim($results[1]);
}
throw new \InvalidArgumentException("could not get MTA940 field with code $code");
}
protected function calculateTransactionFingerprint()
{
$field86 = $this->getField('86');
$field61 = $this->getField('61');
return hash('sha256', $field61 . $field86);
}
/**
* @param string $string
*
* @return string
*/
protected function sanitizeAccount($string)
{
static $crudeReplacements = [
'.' => '',
' ' => '',
'GIRO' => 'P',
];
// crude IBAN to 'old' converter
if (Mt940::$removeIBAN
&& preg_match('#[A-Z]{2}[\d]{2}[A-Z]{4}(.*)#', $string, $results)
&& !empty($results[1])
) {
$string = $results[1];
}
$account = ltrim(
str_replace(
array_keys($crudeReplacements),
$crudeReplacements,
strip_tags(trim($string))
),
'0'
);
if ($account !== '' && strlen($account) < 9 && strpos($account, 'P') === false) {
$account = 'P' . $account;
}
return $account;
}
/**
* @param string $string
*
* @return string
*/
protected function sanitizeAccountName($string)
{
return preg_replace('/[\r\n]+/', '', trim($string));
}
/**
* @param string $string
* @param string $inFormat
*
* @return int
*/
protected function sanitizeTimestamp($string, $inFormat = 'ymd')
{
$date = \DateTime::createFromFormat($inFormat, $string);
$date->setTime(0, 0);
if ($date !== false) {
return (int) $date->format('U');
}
return 0;
}
/**
* @param string $string
*
* @return string
*/
protected function sanitizeDescription($string)
{
return preg_replace('/[\r\n]+/', '', trim($string));
}
/**
* @param string $string
*
* @return string
*/
protected function sanitizeDebitCredit($string)
{
$debitOrCredit = strtoupper(substr((string) $string, 0, 1));
if ($debitOrCredit !== Transaction::DEBIT && $debitOrCredit !== Transaction::CREDIT) {
trigger_error('wrong value for debit/credit (' . $string . ')', E_USER_ERROR);
$debitOrCredit = '';
}
return $debitOrCredit;
}
/**
* @param string $string
*
* @return float
*/
protected function sanitizePrice($string)
{
$floatPrice = ltrim(str_replace(',', '.', strip_tags(trim($string))), '0');
return (float) $floatPrice;
}
}