Lines 93.85% 107 / 114
Functions and Methods 50.00% 4 / 8
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
TatraBankaSimpleMailParser 93.85% 107 / 114 50.00% 4 / 8 60.83 0.00% 0 / 1
 bankDomains 100.00% 1 / 1 100.00% 1 / 1 1
 supports 100.00% 9 / 9 100.00% 1 / 1 3
 parse 94.54% 52 / 55 0.00% 0 / 1 23.09
 parseTimestamp 100.00% 8 / 8 100.00% 1 / 1 4
 firstNotificationBlock 92.00% 23 / 25 0.00% 0 / 1 15.12
 cardPayPairs 88.88% 8 / 9 0.00% 0 / 1 5.03
 mixesProse 75.00% 3 / 4 0.00% 0 / 1 3.14
 cardPayBlock 100.00% 3 / 3 100.00% 1 / 1 6
1<?php
2
3declare(strict_types=1);
4
5namespace Tomaj\BankMailsParser\Parser\TatraBanka;
6
7use DateTimeImmutable;
8use Tomaj\BankMailsParser\Exception\InvalidEmailFormatException;
9use Tomaj\BankMailsParser\MailContent;
10use Tomaj\BankMailsParser\Parser\BankDate;
11use Tomaj\BankMailsParser\Parser\ParserInterface;
12use Tomaj\BankMailsParser\Parser\ParsesBankMail;
13use Tomaj\BankMailsParser\ValueObject\Currency;
14
15final readonly class TatraBankaSimpleMailParser implements ParserInterface
16{
17    use ParsesBankMail;
18
19    private const array FIELD_MAP = [
20        'VS' => 'vs',
21        'RES' => 'res',
22        'AC' => 'ac',
23        'SIGN' => 'sign',
24        'TRES' => 'tres',
25        'CID' => 'cid',
26        'AMT' => 'amount',
27        'CURR' => 'currency',
28        'CC' => 'cc',
29        'TID' => 'tid',
30        'TIMESTAMP' => 'transactionDate',
31        'TXN' => 'txn',
32        'RC' => 'rc',
33        'HMAC' => 'sign',
34    ];
35
36    /**
37     * @return list<string>
38     */
39    #[\Override]
40    public function bankDomains(): array
41    {
42        return ['tatrabanka.sk'];
43    }
44
45    #[\Override]
46    public function supports(string $content, ?string $sender = null, ?string $subject = null): bool
47    {
48        return $this->supportsQuietly(function () use ($content): bool {
49            $block = $this->firstNotificationBlock($this->withoutFreeText($this->scrubUtf8($this->withoutByteOrderMark($content))));
50            if ($block === null) {
51                return false;
52            }
53
54            $keys = [];
55            foreach ($block as [$key]) {
56                $keys[$key] = true;
57            }
58
59            return $this->cardPayBlock($keys);
60        });
61    }
62
63    #[\Override]
64    public function parse(string $content): MailContent
65    {
66        $block = $this->firstNotificationBlock($this->withoutFreeText($this->scrubUtf8($this->requireUniformLineBreaks($content))));
67        if ($block === null) {
68            throw InvalidEmailFormatException::malformedContent(self::class, 'Empty content');
69        }
70
71        $data = [];
72        $seen = [];
73        $sign = null;
74        $hmac = null;
75        foreach ($block as [$key, $value]) {
76            $value = mb_trim($value);
77            if ($key === 'SIGN') {
78                if ($sign !== null && $sign !== $value) {
79                    throw InvalidEmailFormatException::malformedContent(self::class, 'Duplicate CardPay field sign');
80                }
81                $sign = $value;
82
83                continue;
84            }
85            if ($key === 'HMAC') {
86                if ($hmac !== null && $hmac !== $value) {
87                    throw InvalidEmailFormatException::malformedContent(self::class, 'Duplicate CardPay field sign');
88                }
89                $hmac = $value;
90
91                continue;
92            }
93            if (!isset(self::FIELD_MAP[$key])) {
94                continue;
95            }
96
97            $property = self::FIELD_MAP[$key];
98            $data[$property] = $value;
99            $seen[$property][] = $data[$property];
100        }
101        if ($hmac !== null || $sign !== null) {
102            $data['sign'] = $hmac ?? $sign;
103        }
104
105        foreach ($seen as $property => $values) {
106            if (count(array_unique($values)) > 1) {
107                throw InvalidEmailFormatException::malformedContent(self::class, 'Duplicate CardPay field ' . $property);
108            }
109        }
110
111        if (!isset($data['res']) && !isset($data['tres'])) {
112            throw InvalidEmailFormatException::missingRequiredField(self::class, 'RES');
113        }
114
115        $money = null;
116        if (isset($data['amount']) && $data['amount'] !== '') {
117            $currency = isset($data['currency']) && $data['currency'] !== '' ? $data['currency'] : 'EUR';
118            if (Currency::tryFromCode($currency) instanceof Currency) {
119                $money = $this->money($data['amount'], $currency, '.');
120            }
121        }
122
123        $tres = $data['tres'] ?? null;
124        $res = $tres ?? ($data['res'] ?? null);
125
126        $transactionDate = null;
127        if (isset($data['transactionDate']) && $data['transactionDate'] !== '') {
128            $transactionDate = $this->parseTimestamp($data['transactionDate']);
129        }
130
131        return new MailContent(
132            money: $money,
133            transactionDate: $transactionDate,
134            vs: $data['vs'] ?? null,
135            cid: $data['cid'] ?? null,
136            sign: $data['sign'] ?? null,
137            res: $res,
138            ac: $data['ac'] ?? null,
139            cc: $data['cc'] ?? null,
140            tid: $data['tid'] ?? null,
141            txn: $data['txn'] ?? null,
142            rc: $data['rc'] ?? null,
143            tres: $tres,
144        );
145    }
146
147    private function parseTimestamp(string $value): DateTimeImmutable
148    {
149        if (preg_match('/^\d{14}$/', $value) === 1) {
150            $parsed = BankDate::parse($value, '!dmYHis', BankDate::utc());
151            if (!$parsed instanceof \DateTimeImmutable) {
152                throw InvalidEmailFormatException::malformedContent(self::class, 'TIMESTAMP is not a valid date');
153            }
154
155            return $parsed;
156        }
157
158        if (preg_match('/^\d{10}$/', $value) === 1) {
159            return new DateTimeImmutable('@' . $value);
160        }
161
162        throw InvalidEmailFormatException::malformedContent(self::class, 'TIMESTAMP is not a valid date');
163    }
164
165    /**
166     * First contiguous KEY=value region that carries RES or TRES. Quoted lines are ignored.
167     *
168     * @return list<array{0: string, 1: string}>|null
169     */
170    private function firstNotificationBlock(string $content): ?array
171    {
172        $lines = preg_split('/\R/u', $content);
173        if ($lines === false) {
174            return null;
175        }
176
177        /** @var list<array{0: string, 1: string}> $pairs */
178        $pairs = [];
179        $hasResult = false;
180        foreach ($lines as $line) {
181            $bare = preg_replace('/^\x{FEFF}/u', '', $line) ?? $line;
182            if (preg_match('/^[ \t]*>/', $bare) === 1 || trim($bare) === '') {
183                continue;
184            }
185
186            if ($pairs !== [] && $this->mixesProse($bare)) {
187                return $pairs;
188            }
189
190            $linePairs = $this->cardPayPairs($bare);
191            if ($linePairs === null) {
192                if ($hasResult && $pairs !== []) {
193                    return $pairs;
194                }
195                $pairs = [];
196                $hasResult = false;
197
198                continue;
199            }
200
201            foreach ($linePairs as $pair) {
202                if ($pair[0] === 'RES' || $pair[0] === 'TRES') {
203                    $hasResult = true;
204                }
205                $pairs[] = $pair;
206            }
207        }
208
209        if ($hasResult && $pairs !== []) {
210            return $pairs;
211        }
212
213        return null;
214    }
215
216    /**
217     * @return list<array{0: string, 1: string}>|null
218     */
219    private function cardPayPairs(string $line): ?array
220    {
221        $parts = preg_split('/\s+/u', trim($line));
222        if (in_array($parts, [false, [], ['']], true)) {
223            return null;
224        }
225
226        $pairs = [];
227        foreach ($parts as $part) {
228            if (preg_match('/^([A-Z][A-Z0-9_]*)=(.*)$/', $part, $match) !== 1) {
229                continue;
230            }
231            $pairs[] = [$match[1], $match[2]];
232        }
233
234        return $pairs === [] ? null : $pairs;
235    }
236
237    private function mixesProse(string $line): bool
238    {
239        $parts = preg_split('/\s+/u', trim($line));
240        if ($parts === false) {
241            return false;
242        }
243        return array_any($parts, fn(string $part): bool => $part !== '' && preg_match('/^[A-Z][A-Z0-9_]*=/', $part) !== 1);
244    }
245
246    /**
247     * @param array<string, true> $keys
248     */
249    private function cardPayBlock(array $keys): bool
250    {
251        $hasResult = isset($keys['RES']) || isset($keys['TRES']);
252        $hasAnchor = isset($keys['AMT']) || isset($keys['VS']) || isset($keys['HMAC']) || isset($keys['SIGN']);
253
254        return $hasResult && $hasAnchor;
255    }
256}