Lines 97.67% 42 / 43
Functions and Methods 88.88% 8 / 9
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
BankMailsParser 97.67% 42 / 43 88.88% 8 / 9 24 0.00% 0 / 1
 __construct 100.00% 5 / 5 100.00% 1 / 1 3
 registerParser 100.00% 1 / 1 100.00% 1 / 1 1
 prependParser 100.00% 1 / 1 100.00% 1 / 1 1
 parseAll 100.00% 11 / 11 100.00% 1 / 1 6
 parserAcceptsSender 83.33% 5 / 6 0.00% 0 / 1 4.07
 parse 100.00% 6 / 6 100.00% 1 / 1 3
 tryParse 100.00% 5 / 5 100.00% 1 / 1 3
 getParsers 100.00% 1 / 1 100.00% 1 / 1 1
 registerDefaultParsers 100.00% 7 / 7 100.00% 1 / 1 2
1<?php
2
3declare(strict_types=1);
4
5namespace Tomaj\BankMailsParser;
6
7use Tomaj\BankMailsParser\Exception\AmbiguousBankException;
8use Tomaj\BankMailsParser\Exception\ConfigurationException;
9use Tomaj\BankMailsParser\Exception\InvalidEmailFormatException;
10use Tomaj\BankMailsParser\Exception\MultipleTransactionsException;
11use Tomaj\BankMailsParser\Exception\ParseException;
12use Tomaj\BankMailsParser\Exception\UnsupportedBankException;
13use Tomaj\BankMailsParser\Parser\Csob\CsobMailParser;
14use Tomaj\BankMailsParser\Parser\Csob\SkCsobMailParser;
15use Tomaj\BankMailsParser\Parser\ParserInterface;
16use Tomaj\BankMailsParser\Parser\SenderHost;
17use Tomaj\BankMailsParser\Parser\TatraBanka\TatraBankaMailDecryptor;
18use Tomaj\BankMailsParser\Parser\TatraBanka\TatraBankaMailParser;
19use Tomaj\BankMailsParser\Parser\TatraBanka\TatraBankaSimpleMailParser;
20use Tomaj\BankMailsParser\Parser\TatraBanka\TatraBankaStatementMailParser;
21use Tomaj\BankMailsParser\Parser\Vub\VubMailParser;
22
23/**
24 * Facade that selects a parser from the email body.
25 *
26 * When a sender is present, only parsers of that bank are considered. If more than one
27 * of those parsers accepts the body, parsing stops with AmbiguousBankException.
28 * A parser that throws InvalidEmailFormatException is recorded and not replaced by a later parser.
29 * Any other parse error, including ConfigurationException, stops the walk.
30 */
31final class BankMailsParser
32{
33    /**
34     * @var list<ParserInterface>
35     */
36    private array $parsers = [];
37
38    /**
39     * @param list<ParserInterface>|null $parsers Parsers to use. Null registers the built-in parsers.
40     *        The statement parser is included only when $decryptor is set.
41     */
42    public function __construct(
43        ?array $parsers = null,
44        private readonly ?TatraBankaMailDecryptor $decryptor = null,
45    ) {
46        if ($parsers === null) {
47            $this->registerDefaultParsers();
48
49            return;
50        }
51
52        foreach ($parsers as $parser) {
53            $this->registerParser($parser);
54        }
55    }
56
57    public function registerParser(ParserInterface $parser): void
58    {
59        $this->parsers[] = $parser;
60    }
61
62    public function prependParser(ParserInterface $parser): void
63    {
64        array_unshift($this->parsers, $parser);
65    }
66
67    /**
68     * @return list<MailContent>
69     */
70    public function parseAll(string $content, ?string $sender = null, ?string $subject = null): array
71    {
72        $matched = [];
73        foreach ($this->parsers as $parser) {
74            if (!$this->parserAcceptsSender($parser, $sender)) {
75                continue;
76            }
77            if ($parser->supports($content, $sender, $subject)) {
78                $matched[] = $parser;
79            }
80        }
81
82        if (count($matched) > 1) {
83            throw AmbiguousBankException::forParsers(...array_map(static fn(ParserInterface $parser): string => $parser::class, $matched));
84        }
85
86        if ($matched === []) {
87            throw UnsupportedBankException::withSender($sender);
88        }
89
90        return $matched[0]->parseAll($content);
91    }
92
93    private function parserAcceptsSender(ParserInterface $parser, ?string $sender): bool
94    {
95        if ($sender === null || trim($sender) === '') {
96            return true;
97        }
98
99        $domains = $parser->bankDomains();
100        if ($domains === []) {
101            return false;
102        }
103        return array_any($domains, fn($domain): bool => SenderHost::matches($sender, $domain));
104    }
105
106    public function parse(string $content, ?string $sender = null, ?string $subject = null): MailContent
107    {
108        $parsed = $this->parseAll($content, $sender, $subject);
109        if ($parsed === []) {
110            throw InvalidEmailFormatException::malformedContent(self::class, 'Parser returned no transactions');
111        }
112        if (count($parsed) > 1) {
113            throw MultipleTransactionsException::useParseAll(count($parsed));
114        }
115
116        return $parsed[0];
117    }
118
119    public function tryParse(string $content, ?string $sender = null, ?string $subject = null): ?MailContent
120    {
121        try {
122            return $this->parse($content, $sender, $subject);
123        } catch (ConfigurationException $exception) {
124            throw $exception;
125        } catch (ParseException|\InvalidArgumentException|\ValueError|\DateMalformedStringException) {
126            return null;
127        }
128    }
129
130    /**
131     * @return list<ParserInterface>
132     */
133    public function getParsers(): array
134    {
135        return $this->parsers;
136    }
137
138    private function registerDefaultParsers(): void
139    {
140        $this->registerParser(new TatraBankaMailParser());
141        $this->registerParser(new TatraBankaSimpleMailParser());
142        if ($this->decryptor instanceof TatraBankaMailDecryptor) {
143            $this->registerParser(new TatraBankaStatementMailParser($this->decryptor));
144        }
145        $this->registerParser(new CsobMailParser());
146        $this->registerParser(new SkCsobMailParser());
147        $this->registerParser(new VubMailParser());
148    }
149}