FilterTransactions::filter()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 42
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 25
c 1
b 0
f 0
dl 0
loc 42
rs 9.2088
cc 5
nc 5
nop 1
1
<?php
2
declare(strict_types=1);
3
4
5
namespace App\Services\Sync;
6
7
use App\Services\Sync\JobStatus\ProgressInformation;
8
use Log;
9
10
/**
11
 * Class FilterTransactions
12
 */
13
class FilterTransactions
14
{
15
    use ProgressInformation;
16
17
    /** @var array */
18
    private $keys;
19
20
    public function __construct()
21
    {
22
        $this->keys = [];
23
    }
24
25
    /**
26
     * @param array $transactions
27
     *
28
     * @return array
29
     */
30
    public function filter(array $transactions): array
31
    {
32
        $start  = count($transactions);
33
        $return = [];
34
        /** @var array $transaction */
35
        foreach ($transactions as $index => $group) {
36
            $transaction = $group['transactions'][0];
37
            if ('transfer' !== $transaction['type']) {
38
                $return[] = $group;
39
                continue;
40
            }
41
            // if it's a transfer, source + destination are ID.
42
            // amount always positive.
43
            // use datetime
44
            // use description:
45
            $format = '%d/%d(%s)%s@%s';
46
            // account ID's in the right order
47
            $low         = min($transaction['source_id'], $transaction['destination_id']);
48
            $high        = max($transaction['source_id'], $transaction['destination_id']);
49
            $amount      = (string) round($transaction['amount'], 2);
50
            $datetime    = substr($transaction['datetime'], 0, 19); // shave off the milli seconds.
51
            $description = $transaction['description'];
52
            $key         = sprintf($format, $low, $high, $amount, $description, $datetime);
53
            Log::debug(sprintf('Key is "%s"', $key));
54
            if (isset($this->keys[$key])) {
55
                // transaction is double:
56
                Log::info(sprintf('Key is already used: %s', $this->keys[$key]));
57
                continue;
58
            }
59
60
            if (!isset($this->keys[$key])) {
61
                $this->keys[$key] = sprintf('bunq transaction ID #%s', $transaction['bunq_payment_id']);
62
63
                // unset date time because the API doesn't use it anyway:
64
                unset($group['transactions'][0]['datetime']);
65
                $return[] = $group;
66
            }
67
        }
68
        $end = count($return);
69
        $this->addMessage(0, sprintf('Filtered down from %d (possibly duplicate) entries to %d unique transactions.', $start, $end));
70
71
        return $return;
72
    }
73
74
}