Lines 97.05% 264 / 272
Methods 85.71% 36 / 42
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 bankDomains 100.00% 1 / 1 100.00% 1 / 1 1
 supports 100.00% 3 / 3 100.00% 1 / 1 1
 parseMulti 100.00% 20 / 20 100.00% 1 / 1 6
 parseAll 100.00% 4 / 4 100.00% 1 / 1 2
 parse 100.00% 37 / 37 100.00% 1 / 1 13
 lastNumberInPurpose 100.00% 7 / 7 100.00% 1 / 1 5
 multilineSymbol 90.90% 10 / 11 0.00% 0 / 1 9.06
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] parse n/a 0 / 0 n/a 0 / 0 0
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] tryParse 100.00% 5 / 5 100.00% 1 / 1 3
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] parseAll 100.00% 1 / 1 100.00% 1 / 1 1
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] withoutByteOrderMark 100.00% 6 / 6 100.00% 1 / 1 3
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] requireUniformLineBreaks 100.00% 1 / 1 100.00% 1 / 1 1
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] normalizeHtmlLineBreaks 100.00% 4 / 4 100.00% 1 / 1 3
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] scrubUtf8 100.00% 3 / 3 100.00% 1 / 1 2
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] supportsQuietly 100.00% 3 / 3 100.00% 1 / 1 2
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] money 100.00% 3 / 3 100.00% 1 / 1 2
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] moneyOrNull 100.00% 5 / 5 100.00% 1 / 1 4
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] matched 100.00% 8 / 8 100.00% 1 / 1 3
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] group 100.00% 4 / 4 100.00% 1 / 1 2
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] optionalGroup 100.00% 4 / 4 100.00% 1 / 1 3
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] normalizeAccount 100.00% 3 / 3 100.00% 1 / 1 2
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] transactionsOrFail 100.00% 7 / 7 100.00% 1 / 1 2
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] senderDomain 100.00% 1 / 1 100.00% 1 / 1 1
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] bankDomains 0.00% 0 / 1 0.00% 0 / 1 2
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] withoutFreeText 100.00% 1 / 1 100.00% 1 / 1 1
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] assertBalanceChain 78.57% 11 / 14 0.00% 0 / 1 10.98
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] balanceAmount 90.00% 9 / 10 0.00% 0 / 1 5.03
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] maskFreeText 100.00% 1 / 1 100.00% 1 / 1 1
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] splitOutsideFreeText 92.85% 13 / 14 0.00% 0 / 1 7.02
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] field 100.00% 2 / 2 100.00% 1 / 1 1
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] lineValue 100.00% 4 / 4 100.00% 1 / 1 3
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] paymentSymbol 100.00% 5 / 5 100.00% 1 / 1 5
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] rewriteFreeText 97.14% 34 / 35 0.00% 0 / 1 20
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] isFreeTextLabel 100.00% 1 / 1 100.00% 1 / 1 1
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] payerKind 100.00% 13 / 13 100.00% 1 / 1 12
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] leadingLabel 100.00% 3 / 3 100.00% 1 / 1 2
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] isBlankLine 100.00% 3 / 3 100.00% 1 / 1 2
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] couldBeBankLine 100.00% 3 / 3 100.00% 1 / 1 4
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] isBankCloser 100.00% 5 / 5 100.00% 1 / 1 6
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] isExactBalanceLine 100.00% 5 / 5 100.00% 1 / 1 1
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] isDigitSymbolLine 100.00% 2 / 2 100.00% 1 / 1 1
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] isExactAccountLine 100.00% 6 / 6 100.00% 1 / 1 1
 [Tomaj\BankMailsParser\Parser\ParsesBankMail] isTatraBalanceLine 100.00% 3 / 3 100.00% 1 / 1 1
13final readonly class CsobMailParser implements ParserInterface
14{
15    use ParsesBankMail;
16
17    /**
18     * A header is the start of a line. It does not need a blank line in front of it.
19     * A header inside a payer field is blanked with that field, so it does not open a transaction.
20     */
21    private const string TRANSACTION = '/^[ \t\x{00A0}\x{2009}\x{202F}]*Dne[ \t\x{00A0}\x{2009}\x{202F}]+(\d{1,2}\.\d{1,2}\.\d{4}(?:[ T\x{00A0}\x{2009}\x{202F}]\d{1,2}:\d{2})?)[ \t\x{00A0}\x{2009}\x{202F}]+byl(?:a)?[ \t\x{00A0}\x{2009}\x{202F}]+na účtu[ \t\x{00A0}\x{2009}\x{202F}]+([A-Za-z0-9]+)[ \t\x{00A0}\x{2009}\x{202F}]+(?:zaúčtovaná|zaúčtována|zaúčtovaný)[ \t\x{00A0}\x{2009}\x{202F}]+(?:zahraniční transakce\.|hotovostní transakce\.|(?:transakce typu:[ \t\x{00A0}\x{2009}\x{202F}]*|transakce[ \t\x{00A0}\x{2009}\x{202F}]+)?(?:Došlá platba|Příchozí úhrada|Došlá úhrada|SEPA převod|platební kartou))/mu';
22
23    private const string HEADER = '/^[ \t\x{00A0}\x{2009}\x{202F}]*Dne[ \t\x{00A0}\x{2009}\x{202F}]+\d{1,2}\.\d{1,2}\.\d{4}(?:[ T\x{00A0}\x{2009}\x{202F}]\d{1,2}:\d{2})?[ \t\x{00A0}\x{2009}\x{202F}]+byl(?:a)?[ \t\x{00A0}\x{2009}\x{202F}]+na účtu/mu';
24
25    private const string BALANCE = '/Zůstatek na účtu po zaúčtování transakce:[ \t\x{00A0}\x{2009}\x{202F}]*([+-])[ \t\x{00A0}\x{2009}\x{202F}]*((?:\d{1,3}(?:[ \t\x{00A0}\x{2009}\x{202F}]\d{3})*|\d+),\d{2})[ \t\x{00A0}\x{2009}\x{202F}]+([A-Z]{3})\./u';
26
27    private const string ACCOUNT = '[A-Za-z0-9][A-Za-z0-9 \t\x{00A0}\x{2009}\x{202F}\\/-]*';
28
29    /**
30     * @return list<string>
31     */
32    #[\Override]
33    public function bankDomains(): array
34    {
35        return ['csob.cz'];
36    }
37
38    #[\Override]
39    public function supports(string $content, ?string $sender = null, ?string $subject = null): bool
40    {
41        return $this->supportsQuietly(
42            fn(): bool => $this->matched(self::HEADER, $this->withoutFreeText($this->normalizeHtmlLineBreaks($this->withoutByteOrderMark($content)))),
43        );
44    }
45
46    /**
47     * @return list<MailContent>
48     */
49    public function parseMulti(string $content): array
50    {
51        $content = $this->normalizeHtmlLineBreaks($this->requireUniformLineBreaks($content));
52        $chunks = $this->splitOutsideFreeText($content, self::HEADER);
53        $parsed = [];
54        $balances = [];
55        $errors = [];
56        $first = null;
57        $index = 0;
58        foreach ($chunks as $chunk) {
59            if (!$this->matched(self::TRANSACTION, $this->withoutFreeText($chunk))) {
60                continue;
61            }
62            ++$index;
63            try {
64                $parsed[] = $this->parse($chunk);
65                $balances[] = $this->balanceAmount($chunk, self::BALANCE);
66            } catch (InvalidEmailFormatException $exception) {
67                $first ??= $exception;
68                $errors[] = sprintf('transaction %d: %s', $index, $exception->getMessage());
69            }
70        }
71
72        $parsed = $this->transactionsOrFail($parsed, $errors, $first);
73        if (count($parsed) > 1 && $this->matched(self::BALANCE, $content)) {
74            $this->assertBalanceChain($balances, $parsed);
75        }
76
77        return $parsed;
78    }
79
80    #[\Override]
81    public function parseAll(string $content): array
82    {
83        $parsed = $this->parseMulti($content);
84        if ($parsed === []) {
85            throw InvalidEmailFormatException::malformedContent(self::class, 'Could not find transaction pattern');
86        }
87
88        return $parsed;
89    }
90
91    #[\Override]
92    public function parse(string $content): MailContent
93    {
94        $original = $this->normalizeHtmlLineBreaks($this->requireUniformLineBreaks($content));
95        $receiverMessage = $this->lineValue($original, 'Zpráva příjemci');
96        $content = $this->withoutFreeText($original);
97        if (!$this->matched(self::TRANSACTION, $content, $result)) {
98            throw InvalidEmailFormatException::malformedContent(self::class, 'Could not find transaction pattern');
99        }
100
101        $transactionDate = BankDate::parseFirst($this->group($result, 1), ['!j.n.Y G:i', '!j.n.Y'], BankDate::bratislava());
102        $accountNumber = $this->group($result, 2);
103
104        $sourceAccountNumber = null;
105        if ($this->matched($this->field('Účet protistrany(?:\/IBAN)*:', '(' . self::ACCOUNT . ')'), $content, $counterparty)) {
106            $sourceAccountNumber = mb_trim($this->group($counterparty, 1), " \t\n\r\0\x0B\u{00A0}\u{2009}\u{202F}");
107        }
108
109        $money = null;
110        if ($this->matched($this->field('Částka:', '([+-])[ \t\x{00A0}\x{2009}\x{202F}]*(.*?)[ \t\x{00A0}\x{2009}\x{202F}]+([A-Z]{3})\b'), $content, $amount)) {
111            $signed = ($this->group($amount, 1) === '-' ? '-' : '') . $this->group($amount, 2);
112            $money = $this->moneyOrNull($signed, $this->group($amount, 3), ',');
113        }
114
115        $vs = $this->multilineSymbol($original, 'variable');
116        $identified = $this->multilineSymbol($original, 'identification');
117        if ($identified !== null) {
118            $vs = $identified;
119        }
120        // 4.1.0 fallbacks. Payer text can supply vs only. Amount, account, and date stay on the bank lines.
121        if ($vs === null && $this->matched('/vs([0-9]{1,10})(?!\d)/i', $original, $symbol)) {
122            $vs = $this->group($symbol, 1);
123        }
124        if ($vs === null && $this->matched('/v\.s\.([0-9]{1,10})(?!\d)/i', $original, $symbol)) {
125            $vs = $this->group($symbol, 1);
126        }
127        if ($vs === null && $this->matched('/Zpráva příjemci:.*\b([0-9]{1,10})\b.*/i', $original, $symbol)) {
128            $vs = $this->group($symbol, 1);
129        }
130        $vs ??= $this->multilineSymbol($original, 'purpose') ?? $this->lastNumberInPurpose($original);
131
132        $ks = null;
133        if ($this->matched($this->field('Konstantní symbol:', '([0-9]+)'), $original, $symbol)) {
134            $ks = $this->paymentSymbol($this->group($symbol, 1));
135        }
136
137        return new MailContent(
138            money: $money,
139            transactionDate: $transactionDate,
140            accountNumber: $accountNumber,
141            sourceAccountNumber: $sourceAccountNumber,
142            vs: $vs,
143            ks: $ks,
144            receiverMessage: $receiverMessage,
145        );
146    }
147
148    /**
149     * Last 1–10 digit number between Účel platby and Zůstatek, as in 4.1.0.
150     * Without Zůstatek the footer is ignored. A number glued to letters is not a symbol.
151     * A blank line does not stop the search: 4.1.0 uses dotall up to Zůstatek.
152     */
153    private function lastNumberInPurpose(string $original): ?string
154    {
155        if (!str_contains($original, 'Zůstatek') || preg_match('/Účel platby:(.*?)Zůstatek/su', $original, $match) !== 1) {
156            return null;
157        }
158        $text = $match[1];
159        if (preg_match_all('/\b([0-9]{1,10})\b/u', $text, $numbers) < 1) {
160            return null;
161        }
162
163        $last = end($numbers[1]);
164
165        return is_string($last) ? $last : null;
166    }
167
168    /**
169     * `/m` on these patterns has no effect: they do not use `^` or `$`.
170     * Infection ignores PregMatchRemoveFlags for this method only.
171     */
172    private function multilineSymbol(string $original, string $which): ?string
173    {
174        $pattern = match ($which) {
175            'variable' => '/Variabilní symbol: ([0-9]{1,10})(?!\d)/m',
176            'identification' => '/Identifikace: ([0-9]{1,10})(?!\d)/m',
177            'purpose' => '/Účel platby: ([0-9]{1,10})(?!\d)/m',
178            default => null,
179        };
180        if ($pattern === null || !$this->matched($pattern, $original, $symbol)) {
181            return null;
182        }
183        $value = $this->group($symbol, 1);
184        if ($which === 'variable' && (int) $value === 0) {
185            return null;
186        }
187
188        return $value;
189    }
190}

From Tomaj\BankMailsParser\Parser\ParsesBankMail

14trait ParsesBankMail
15{
16    abstract public function parse(string $content): MailContent;
17
18    /**
19     * Invalid input returns null. ConfigurationException is a setup error and is rethrown.
20     * TypeError and Error are programmer errors and are not caught.
21     */
22    public function tryParse(string $content): ?MailContent
23    {
24        try {
25            return $this->parse($content);
26        } catch (ConfigurationException $exception) {
27            throw $exception;
28        } catch (ParseException|\InvalidArgumentException|\ValueError|\DateMalformedStringException) {
29            return null;
30        }
31    }
32
33    /**
34     * @return list<MailContent>
35     */
36    public function parseAll(string $content): array
37    {
38        return [$this->parse($content)];
39    }
40
41    /**
42     * Drop a leading BOM. CRLF becomes LF. Lone CR, VT, FF, U+0085, U+2028 and U+2029
43     * become LF only when the mail has no LF at all. A mail that already has LF keeps
44     * those characters as ordinary text: they do not split a line and they do not open
45     * a new transaction. supports() uses this and does not throw.
46     *
47     * The `/m` flag is required: a BOM after a header is still a BOM.
48     *
49     * @internal
50     */
51    protected function withoutByteOrderMark(string $content): string
52    {
53        $stripped = preg_replace('/^\x{FEFF}/mu', '', $content);
54        $content = is_string($stripped) ? $stripped : $content;
55        $content = str_replace("\r\n", "\n", $content);
56        if (str_contains($content, "\n")) {
57            return $content;
58        }
59
60        return str_replace(["\r", "\v", "\f", "\u{0085}", "\u{2028}", "\u{2029}"], "\n", $content);
61    }
62
63    /**
64     * Normalize line breaks. Exotic separators stay in a mail that already has LF.
65     * They are ordinary characters there and cannot open a transaction.
66     *
67     * @internal
68     */
69    protected function requireUniformLineBreaks(string $content): string
70    {
71        return $this->withoutByteOrderMark($content);
72    }
73
74    /**
75     * A single-line HTML ČSOB body uses `<br>`, `</p>` and `</div>` as line breaks.
76     * Turn those into newlines, then drop the remaining tags, so a header can still
77     * start a line. `<br>` does not stay inside an account number.
78     *
79     * @internal
80     */
81    protected function normalizeHtmlLineBreaks(string $content): string
82    {
83        $broken = preg_replace('/<br\s*\/?>|<\/(?:p|div|tr)\s*>|<(?:p|div|tr)\b[^>]*>/iu', "\n", $content);
84        $content = is_string($broken) ? $broken : $content;
85        $stripped = preg_replace('/<[^>\n]*>/', '', $content);
86
87        return is_string($stripped) ? $stripped : $content;
88    }
89
90    /**
91     * Tatra and CardPay patterns use `/u`. Invalid bytes are replaced so a
92     * Windows-1250 body still parses, the way 4.x did without `/u`.
93     *
94     * @internal
95     */
96    protected function scrubUtf8(string $content): string
97    {
98        if (mb_check_encoding($content, 'UTF-8')) {
99            return $content;
100        }
101
102        return mb_scrub($content, 'UTF-8');
103    }
104
105    /**
106     * supports() never throws. A PCRE limit on a huge mail is "not this bank".
107     *
108     * @param \Closure(): bool $probe
109     *
110     * @internal
111     */
112    protected function supportsQuietly(\Closure $probe): bool
113    {
114        try {
115            return $probe();
116        } catch (\Throwable) {
117            return false;
118        }
119    }
120
121    /**
122     * Turn a decimal string into Money. Invalid amounts become InvalidEmailFormatException.
123     */
124    protected function money(string $amount, Currency|string $currency, ?string $decimalSeparator = null): Money
125    {
126        try {
127            return Money::fromDecimalString($amount, $currency, $decimalSeparator);
128        } catch (\InvalidArgumentException $exception) {
129            throw InvalidEmailFormatException::malformedContent(static::class, $exception->getMessage(), $exception);
130        }
131    }
132
133    /**
134     * Same as money(), except a missing, unreadable, or unknown-currency amount is null.
135     * The rest of the transaction is still returned, as in 4.x.
136     */
137    protected function moneyOrNull(string $amount, Currency|string $currency, ?string $decimalSeparator = null): ?Money
138    {
139        if (is_string($currency) && !Currency::tryFromCode($currency) instanceof Currency) {
140            return null;
141        }
142
143        try {
144            return $this->money($amount, $currency, $decimalSeparator);
145        } catch (InvalidEmailFormatException) {
146            return null;
147        }
148    }
149
150    /**
151     * @param array<int|string, string>|null $matches
152     *
153     * @internal
154     */
155    protected function matched(string $pattern, string $subject, ?array &$matches = null): bool
156    {
157        $captured = [];
158        $result = preg_match($pattern, $subject, $captured);
159        if ($result === false) {
160            throw InvalidEmailFormatException::malformedContent(static::class, 'Regular expression failed: ' . preg_last_error_msg());
161        }
162
163        if ($result === 1) {
164            /** @var array<int|string, string> $captured */
165            $matches = $captured;
166
167            return true;
168        }
169
170        return false;
171    }
172
173    /**
174     * @param array<int|string, string>|null $matches
175     *
176     * @internal
177     */
178    protected function group(?array $matches, int $index): string
179    {
180        $value = $matches[$index] ?? null;
181        if (!is_string($value)) {
182            throw InvalidEmailFormatException::malformedContent(static::class, 'Missing regular expression capture');
183        }
184
185        return $value;
186    }
187
188    /**
189     * @param array<int|string, string>|null $matches
190     *
191     * @internal
192     */
193    private function optionalGroup(?array $matches, int $index): ?string
194    {
195        $value = $matches[$index] ?? null;
196        if (!is_string($value) || $value === '') {
197            return null;
198        }
199
200        return $value;
201    }
202
203    /** @internal */
204    private function normalizeAccount(string $value): string
205    {
206        $spaced = str_replace(["\u{00A0}", "\u{2009}", "\u{202F}", "\t"], ' ', $value);
207        $collapsed = preg_replace('/ {2,}/', ' ', trim($spaced));
208
209        return is_string($collapsed) ? $collapsed : trim($spaced);
210    }
211
212    /**
213     * @param list<MailContent> $parsed
214     * @param list<string> $errors
215     *
216     * @return list<MailContent>
217     *
218     * @internal
219     */
220    private function transactionsOrFail(array $parsed, array $errors, ?\Throwable $previous = null): array
221    {
222        if ($errors !== []) {
223            throw InvalidEmailFormatException::malformedContent(
224                static::class,
225                'Could not parse every transaction: ' . implode('; ', $errors),
226                $previous,
227            );
228        }
229
230        return $parsed;
231    }
232
233    /** @internal */
234    protected function senderDomain(string $sender, string $domain): bool
235    {
236        return SenderHost::matches($sender, $domain);
237    }
238
239    /**
240     * @return list<string>
241     */
242    public function bankDomains(): array
243    {
244        return [];
245    }
246
247    /**
248     * Payer-controlled text. Amount, currency, account and date are never read from it.
249     *
250     * @internal
251     */
252    protected function withoutFreeText(string $content): string
253    {
254        return $this->rewriteFreeText($content, false);
255    }
256
257    /**
258     * When a ČSOB mail has more than one transaction and at least one balance line,
259     * each transaction must carry a balance and balance[n-1] + amount[n] = balance[n].
260     *
261     * @param list<?Money> $balances
262     * @param list<MailContent> $parsed
263     *
264     * @internal
265     */
266    private function assertBalanceChain(array $balances, array $parsed): void
267    {
268        $count = count($parsed);
269        for ($index = 0; $index < $count; ++$index) {
270            if (!$balances[$index] instanceof Money) {
271                throw InvalidEmailFormatException::malformedContent(static::class, 'Transaction is missing a balance line');
272            }
273        }
274
275        for ($index = 1; $index < $count; ++$index) {
276            $previous = $balances[$index - 1];
277            $current = $balances[$index];
278            $amount = $parsed[$index]->money;
279            if (!$previous instanceof Money || !$current instanceof Money || !$amount instanceof Money) {
280                throw InvalidEmailFormatException::malformedContent(static::class, 'Balance does not match the previous transaction');
281            }
282            if (!$previous->currency->equals($current->currency) || !$previous->currency->equals($amount->currency)) {
283                throw InvalidEmailFormatException::malformedContent(static::class, 'Balance does not match the previous transaction');
284            }
285            if ($previous->amount + $amount->amount !== $current->amount) {
286                throw InvalidEmailFormatException::malformedContent(static::class, 'Balance does not match the previous transaction');
287            }
288        }
289    }
290
291    /**
292     * The bank prints one balance at the end of the transaction. A second exact
293     * balance line in the same chunk is rejected.
294     *
295     * @internal
296     */
297    private function balanceAmount(string $chunk, string $pattern): ?Money
298    {
299        $found = preg_match_all($pattern, $chunk, $matches, PREG_SET_ORDER);
300        if ($found === false) {
301            throw InvalidEmailFormatException::malformedContent(static::class, 'Regular expression failed: ' . preg_last_error_msg());
302        }
303        if ($found > 1) {
304            throw InvalidEmailFormatException::malformedContent(static::class, 'Transaction has more than one balance line');
305        }
306        if ($found !== 1) {
307            return null;
308        }
309
310        $row = $matches[0];
311        $signed = (($row[1] ?? '') === '-' ? '-' : '') . ($row[2] ?? '');
312
313        return $this->money($signed, $row[3] ?? '', ',');
314    }
315
316    /**
317     * Same byte length as $content. Free-text lines become spaces so a later match offset stays valid.
318     *
319     * @internal
320     */
321    private function maskFreeText(string $content): string
322    {
323        return $this->rewriteFreeText($content, true);
324    }
325
326    /**
327     * @return list<string>
328     *
329     * @internal
330     */
331    private function splitOutsideFreeText(string $content, string $pattern): array
332    {
333        $masked = $this->maskFreeText($content);
334        $found = preg_match_all($pattern, $masked, $matches, PREG_OFFSET_CAPTURE);
335        if ($found === false || $found === 0) {
336            return [$content];
337        }
338
339        $chunks = [];
340        $total = count($matches[0]);
341        for ($index = 0; $index < $total; ++$index) {
342            $start = $matches[0][$index][1] ?? null;
343            $next = $matches[0][$index + 1][1] ?? null;
344            if (!is_int($start)) {
345                continue;
346            }
347            $end = is_int($next) ? $next : strlen($content);
348            $chunks[] = substr($content, $start, $end - $start);
349        }
350
351        return $chunks === [] ? [$content] : $chunks;
352    }
353
354    /**
355     * A label at the start of a line, with the shared whitespace class on both sides.
356     * One builder, so a duplicated `*` class is not copied into every parser.
357     *
358     * @internal
359     */
360    private function field(string $label, string $value): string
361    {
362        $space = MailWhitespace::WS;
363
364        return '/^' . $space . $label . $space . $value . '/mu';
365    }
366
367    /** @internal */
368    private function lineValue(string $content, string $labelPattern): ?string
369    {
370        if (!$this->matched($this->field($labelPattern . ':', '(.*)$'), $content, $matches)) {
371            return null;
372        }
373
374        $value = mb_trim($this->group($matches, 1), " \t\n\r\0\x0B\u{00A0}\u{2009}\u{202F}");
375
376        return $value === '' ? null : $value;
377    }
378
379    /** @internal */
380    private function paymentSymbol(string $digits, ?int $maxDigits = 10): ?string
381    {
382        if ($digits === '' || preg_match('/^\d+$/', $digits) !== 1) {
383            return null;
384        }
385        if ($maxDigits !== null && strlen($digits) > $maxDigits) {
386            return null;
387        }
388
389        return $digits;
390    }
391
392    /**
393     * Payer-written fields.
394     *
395     * ČSOB CZ: Název protistrany, Adresa protistrany, Adresa plátce, Zpráva příjemci,
396     * Účel platby, Identifikace, Reference plátce.
397     * ČSOB SK: názov protiúčtu, meno protiúčtu, informácia pre príjemcu, referencia platiteľa.
398     * Tatra: Informacia pre prijemcu, Popis transakcie, popis, Referencia platitela.
399     * VÚB fixtures have no payer prose field.
400     *
401     * A blank line, or a line of spaces, tabs or NBSP, ends the field.
402     * An arbitrary "Word:" does not. A closing line has to be the bank's own shape:
403     * the full balance sentence, a digits-only symbol line, an account line, or a Tatra balance line.
404     * Lines inside the field are blanked when bank data is read. They do not reject the mail.
405     */
406    private function rewriteFreeText(string $content, bool $mask): string
407    {
408        $parts = preg_split('/(\n)/', $content, -1, PREG_SPLIT_DELIM_CAPTURE);
409        if ($parts === false) {
410            return $content;
411        }
412
413        $active = null;
414        $out = '';
415        foreach ($parts as $part) {
416            if ($part === "\n") {
417                if ($mask || $active === null) {
418                    $out .= $part;
419                }
420
421                continue;
422            }
423
424            if ($active !== null && $this->isBlankLine($part)) {
425                $active = null;
426                $out .= $part;
427
428                continue;
429            }
430
431            // A continuation such as "a" cannot be a label, a closer, or a forged bank line.
432            // Skipping the regexes keeps a long purpose field from scanning every pattern per line.
433            if ($active !== null && !$this->couldBeBankLine($part)) {
434                $out .= $mask ? str_repeat(' ', strlen($part)) : '';
435
436                continue;
437            }
438
439            $next = $this->payerKind($part);
440            if ($active !== null && $next !== null) {
441                $active = $next;
442                $out .= $mask ? str_repeat(' ', strlen($part)) : '';
443
444                continue;
445            }
446
447            if ($active !== null && $this->isBankCloser($part, $active)) {
448                $active = null;
449                $out .= $part;
450
451                continue;
452            }
453
454            if ($next !== null) {
455                $active = $next;
456                $out .= $mask ? str_repeat(' ', strlen($part)) : '';
457
458                continue;
459            }
460
461            if ($active !== null) {
462                $out .= $mask ? str_repeat(' ', strlen($part)) : '';
463
464                continue;
465            }
466
467            $out .= $part;
468        }
469
470        return $out;
471    }
472
473    /** @internal */
474    private function isFreeTextLabel(string $line): bool
475    {
476        return $this->payerKind($line) !== null;
477    }
478
479    private function payerKind(string $line): ?string
480    {
481        $label = $this->leadingLabel($line);
482        if ($label === null) {
483            return null;
484        }
485
486        return match (true) {
487            preg_match('/^(?:název protistrany|adresa plátce|adresa platcu|názov protiúčtu|meno protiúčtu)$/ui', $label) === 1 => 'name',
488            preg_match('/^adresa protistrany$/ui', $label) === 1 => 'address',
489            preg_match('/^zpráva příjemci$/ui', $label) === 1 => 'message',
490            preg_match('/^účel platby$/ui', $label) === 1 => 'purpose',
491            preg_match('/^identifikace$/ui', $label) === 1 => 'identification',
492            preg_match('/^informácia pre príjemcu$/ui', $label) === 1 => 'sk-message',
493            preg_match('/^informacia pre prijemcu$/ui', $label) === 1 => 'tatra-message',
494            preg_match('/^(?:popis transakcie|popis)$/ui', $label) === 1 => 'tatra-description',
495            preg_match('/^(?:reference plátce|referencia platiteľa|referencia platitela)$/ui', $label) === 1 => 'reference',
496            default => null,
497        };
498    }
499
500    /**
501     * Possessive leading whitespace: a multi-megabyte line of spaces must not backtrack.
502     */
503    private function leadingLabel(string $line): ?string
504    {
505        if (preg_match('/^[ \t\x{00A0}\x{2009}\x{202F}\x{FEFF}]*+([^\n:]{1,80})[ \t\x{00A0}\x{2009}\x{202F}]*:/u', $line, $match) !== 1) {
506            return null;
507        }
508
509        return $match[1];
510    }
511
512    private function isBlankLine(string $line): bool
513    {
514        if ($line === '') {
515            return true;
516        }
517
518        return preg_match('/^[ \t\x{00A0}\x{2009}\x{202F}\x{FEFF}]*$/u', $line) === 1;
519    }
520
521    /**
522     * A line with no colon and no date or "Dne"/"dňa" cannot be a bank closer or a forged header.
523     */
524    private function couldBeBankLine(string $line): bool
525    {
526        if (str_contains($line, ':') || str_contains($line, 'Dne') || str_contains($line, 'dňa')) {
527            return true;
528        }
529
530        return preg_match('/\d/u', $line) === 1;
531    }
532
533    /**
534     * A closing line is the bank's own line, not a word the payer can type.
535     * Bare `Zůstatek`, `zostatok`, or `banka:` do not close the field.
536     * Tatra `uctovny zostatok` / `aktualny zostatok` / `disponibilny zostatok` do.
537     */
538    private function isBankCloser(string $line, string $kind): bool
539    {
540        if ($this->isExactBalanceLine($line) || $this->isDigitSymbolLine($line) || $this->isExactAccountLine($line)) {
541            return true;
542        }
543
544        if ($kind === 'tatra-message' || $kind === 'tatra-description') {
545            return $this->isTatraBalanceLine($line);
546        }
547
548        return false;
549    }
550
551    private function isExactBalanceLine(string $line): bool
552    {
553        $ws = MailWhitespace::WS;
554        $amount = '[+-]' . $ws . '(?:\d{1,3}(?:[ \t\x{00A0}\x{2009}\x{202F}]\d{3})*|\d+),\d{2}';
555        $cz = 'zůstatek na účtu po zaúčtování transakce:' . $ws . $amount . $ws . '[A-Z]{3}\.';
556        $sk = 'zostatok na účte po zaúčtovaní sumy platobnej operácie:' . $ws . $amount . $ws . '[A-Z]{3}\.?';
557
558        return preg_match('/^' . $ws . '(?:' . $cz . '|' . $sk . ')' . $ws . '$/ui', $line) === 1;
559    }
560
561    private function isDigitSymbolLine(string $line): bool
562    {
563        $ws = MailWhitespace::WS;
564
565        return preg_match('/^' . $ws . '(?:variabilní symbol|konstantní symbol|specifický symbol)' . $ws . ':' . $ws . '\d+' . $ws . '$/ui', $line) === 1;
566    }
567
568    private function isExactAccountLine(string $line): bool
569    {
570        $ws = MailWhitespace::WS;
571        $domestic = '\d{1,10}(?:-\d{1,10})?\/\d{4}';
572        $iban = '[A-Z]{2}\d{2}(?:[ \t\x{00A0}\x{2009}\x{202F}]?[A-Z0-9]{1,4})+';
573        $account = '(?:' . $iban . '|' . $domestic . ')';
574        $labels = 'účet protistrany(?:\/iban)?|protiúčet|z účtu';
575
576        return preg_match('/^' . $ws . '(?:' . $labels . ')' . $ws . ':' . $ws . $account . $ws . '$/ui', $line) === 1;
577    }
578
579    /**
580     * Tatra prints the balance without a sign: `aktualny zostatok: 142,11 EUR`.
581     * Deleting this rule leaves a later transaction sentence inside the payer message.
582     */
583    private function isTatraBalanceLine(string $line): bool
584    {
585        $ws = MailWhitespace::WS;
586        $amount = '[+-]?' . $ws . '(?:\d{1,3}(?:[ \t\x{00A0}\x{2009}\x{202F}]\d{3})*|\d+),\d{2}';
587
588        return preg_match('/^' . $ws . '(?:uctovny zostatok|aktualny zostatok|disponibilny zostatok)' . $ws . ':' . $ws . $amount . $ws . '[A-Za-z]{3}' . $ws . '$/u', $line) === 1;
589    }
590}