Passed
Branch master (2117c8)
by Hirofumi
97:26 queued 41:41
created

SendEmail::__construct()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
nc 1
nop 1
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Shippinno\Email;
5
6
use Psr\Log\LoggerAwareTrait;
7
use Psr\Log\LoggerInterface;
8
use Psr\Log\NullLogger;
9
use Tanigami\ValueObjects\Web\Email;
10
use Throwable;
11
12
abstract class SendEmail
13
{
14
    use LoggerAwareTrait;
15
16
    /**
17
     * @param LoggerInterface|null $logger
18
     */
19 4
    public function __construct(
20
        LoggerInterface $logger = null
21
    ) {
22 4
        $this->setLogger(is_null($logger) ? new NullLogger : $logger);
23 4
    }
24
25
    /**
26
     * @param Email $email
27
     * @param int $maxAttempts
28
     * @param SmtpConfiguration|null $smtpConfiguration
29
     * @return int
30
     * @throws EmailNotSentException
31
     * @throws Throwable
32
     */
33 3
    public function execute(Email $email, int $maxAttempts = 1, SmtpConfiguration $smtpConfiguration = null): int
34
    {
35 3
        for ($i = 1; $i <= $maxAttempts; $i++) {
36
            try {
37 3
                return $this->doExecute($email, $smtpConfiguration);
38 2
            } catch (EmailNotSentException|Throwable $e) {
39 2
                if ($i < $maxAttempts) {
40 1
                    continue;
41
                }
42 2
                $this->logger->debug(sprintf('Gave up sending an email after reattempting %d times.', $i), [
43 2
                    'subject' => $email->subject(),
44 2
                    'exception' => $e,
45
                ]);
46 2
                throw $e;
47
            }
48
        }
49
    }
50
51
    /**
52
     * @param Email $email
53
     * @param SmtpConfiguration|null $smtpConfiguration
54
     * @return int
55
     * @throws EmailNotSentException
56
     */
57
    abstract protected function doExecute(Email $email, SmtpConfiguration $smtpConfiguration = null): int;
58
}
59