Skip to content

Custom parser ​

A bank the library does not support yet needs a class that implements ParserInterface. Register it on the facade and it takes part in detection like the built-in parsers. This recipe adds a parser for the fictional "Example banka" in the application's own namespace.

Source: examples/custom-parser

The mail ​

text
Dear client,

Incoming payment 24.11.2026
Amount: 49.90 EUR
From account: SK3112000000198742637541
Reference: 2026001234

Example banka

The parser ​

php
<?php

declare(strict_types=1);

namespace App;

use Tomaj\BankMailsParser\Exception\InvalidEmailFormatException;
use Tomaj\BankMailsParser\MailContent;
use Tomaj\BankMailsParser\Parser\ParserInterface;
use Tomaj\BankMailsParser\Parser\ParsesBankMail;

/**
 * Parser for the (fictional) Example banka, whose notification looks like this:
 *
 *   Incoming payment 24.11.2026
 *   Amount: 49.90 EUR
 *   From account: SK3112000000198742637541
 *   Reference: 2026001234
 */
final readonly class ExampleBankMailParser implements ParserInterface
{
    // tryParse(), parseAll() (one transaction) and money() come from the trait
    use ParsesBankMail;

    private const string HEADER = '/^Incoming payment (\d{1,2}\.\d{1,2}\.\d{4})$/m';

    #[\Override]
    public function bankDomains(): array
    {
        return ['bank.example'];
    }

    #[\Override]
    public function supports(string $content, ?string $sender = null, ?string $subject = null): bool
    {
        return preg_match(self::HEADER, $content) === 1;
    }

    public function parse(string $content): MailContent
    {
        if (preg_match(self::HEADER, $content, $header) !== 1) {
            throw InvalidEmailFormatException::malformedContent(self::class, 'Header not found');
        }
        if (preg_match('/^Amount: ([\d.]+) ([A-Z]{3})$/m', $content, $amount) !== 1) {
            throw InvalidEmailFormatException::missingRequiredField(self::class, 'Amount');
        }

        $date = \DateTimeImmutable::createFromFormat('!j.n.Y', $header[1], new \DateTimeZone('Europe/Bratislava'));

        return new MailContent(
            money: $this->money($amount[1], $amount[2], '.'),
            transactionDate: $date === false ? null : $date,
            accountNumber: $this->line($content, 'From account'),
            vs: $this->line($content, 'Reference'),
        );
    }

    private function line(string $content, string $label): ?string
    {
        return preg_match('/^' . preg_quote($label, '/') . ': (.+)$/m', $content, $match) === 1 ? $match[1] : null;
    }
}

ParserInterface asks for three methods:

MethodContract
bankDomains(): list<string>The hosts the bank mails from. With a sender, the facade asks this parser only when the sender's host is one of them or its subdomain. An empty list means the parser is used only when no sender is passed
supports($content, $sender, $subject): boolWhether the body is this bank's mail. Look for a line only the bank writes, anchored at the start of a line, and do not throw
parseAll($content): list<MailContent>Every transaction. Throw InvalidEmailFormatException when the mail is recognised but cannot be read

The ParsesBankMail trait supplies parseAll() (one transaction from your parse()), tryParse(), an empty bankDomains(), and money(), which turns an invalid amount into InvalidEmailFormatException instead of leaking InvalidArgumentException. Its other methods are internal.

The code ​

php
<?php

declare(strict_types=1);

// A parser for a bank the library does not support, registered next to the built-in parsers.

require __DIR__ . '/vendor/autoload.php';

use App\ExampleBankMailParser;
use Tomaj\BankMailsParser\BankMailsParser;
use Tomaj\BankMailsParser\Exception\ParseException;

$parser = new BankMailsParser();            // the built-in parsers
$parser->registerParser(new ExampleBankMailParser());

foreach ($parser->getParsers() as $registered) {
    echo 'parser: ', $registered::class, ' (', implode(', ', $registered->bankDomains()), ")\n";
}

$mail = $parser->parse((string) file_get_contents(__DIR__ . '/mails/example-bank.txt'), 'notify@bank.example');
echo "\nexample-bank.txt\n";
echo '  money            ', $mail->money?->format(), "\n";
echo '  transactionDate  ', $mail->transactionDate?->format('Y-m-d'), "\n";
echo '  accountNumber    ', $mail->accountNumber, "\n";
echo '  vs               ', $mail->vs, "\n";

try {
    $parser->parse((string) file_get_contents(__DIR__ . '/mails/example-bank-broken.txt'), 'notify@bank.example');
} catch (ParseException $e) {
    echo "\nexample-bank-broken.txt\n  ", $e->getMessage(), "\n";
}

// Only the parser for the sender's domain is asked: the same mail from another domain is not parsed.
$other = $parser->tryParse((string) file_get_contents(__DIR__ . '/mails/example-bank.txt'), 'notify@other.example');
echo "\nfrom other.example: ", $other === null ? 'null' : 'parsed', "\n";

The output ​

text
parser: Tomaj\BankMailsParser\Parser\TatraBanka\TatraBankaMailParser (tatrabanka.sk)
parser: Tomaj\BankMailsParser\Parser\TatraBanka\TatraBankaSimpleMailParser (tatrabanka.sk)
parser: Tomaj\BankMailsParser\Parser\Csob\CsobMailParser (csob.cz)
parser: Tomaj\BankMailsParser\Parser\Csob\SkCsobMailParser (csob.sk)
parser: Tomaj\BankMailsParser\Parser\Vub\VubMailParser (vub.sk)
parser: App\ExampleBankMailParser (bank.example)

example-bank.txt
  money            49.90 EUR
  transactionDate  2026-11-24
  accountNumber    SK3112000000198742637541
  vs               2026001234

example-bank-broken.txt
  Parser App\ExampleBankMailParser: required field "Amount" is missing or invalid

from other.example: null

Notes ​

  • registerParser() appends, prependParser() inserts in front. Order does not decide anything when only one parser matches; it is the order of the list getParsers() returns.
  • new BankMailsParser([$parser]) uses only the parsers you pass; new BankMailsParser() (or null) registers the built-in ones.
  • If your supports() also accepts another bank's mail, the facade throws AmbiguousBankException for it. Make the check specific, and pass the sender so the domain filter runs first.
  • Worth sharing? Adding a new bank describes how to contribute a parser to the library, with fixtures and tests.

Released under the MIT License.