Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
25 / 25
100.00% covered (success)
100.00%
6 / 6
CRAP
100.00% covered (success)
100.00%
1 / 1
Mailer
100.00% covered (success)
100.00%
25 / 25
100.00% covered (success)
100.00%
6 / 6
7
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 send
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
2
 getFromAddress
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 setFromAddress
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getFromName
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 setFromName
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3declare(strict_types=1);
4
5namespace Engelsystem\Mail;
6
7use Psr\Log\LoggerInterface;
8use Symfony\Component\Mailer\MailerInterface;
9use Symfony\Component\Mime\Email;
10use Throwable;
11
12class Mailer
13{
14    protected string $fromAddress = '';
15
16    protected ?string $fromName = null;
17
18    public function __construct(protected LoggerInterface $log, protected MailerInterface $mailer)
19    {
20    }
21
22    /**
23     * Send the mail
24     *
25     * @param string|string[] $to
26     */
27    public function send(string|array $to, string $subject, string $body): bool
28    {
29        $message = (new Email())
30            ->to(...(array) $to)
31            ->from(sprintf('%s <%s>', $this->fromName, $this->fromAddress))
32            ->subject($subject)
33            ->text($body);
34
35        try {
36            $this->mailer->send($message);
37        } catch (Throwable $e) {
38            $this->log->error(
39                'Unable to send e-mail "{subject}" to {to} in {file}:{line}: {type}: {message}',
40                [
41                    'subject' => $subject,
42                    'to' => $to,
43                    'file' => $e->getFile(),
44                    'line' => $e->getLine(),
45                    'type' => get_class($e),
46                    'message' => $e->getMessage(),
47                ]
48            );
49
50            return false;
51        }
52
53        return true;
54    }
55
56    public function getFromAddress(): string
57    {
58        return $this->fromAddress;
59    }
60
61    public function setFromAddress(string $fromAddress): void
62    {
63        $this->fromAddress = $fromAddress;
64    }
65
66    public function getFromName(): string
67    {
68        return $this->fromName;
69    }
70
71    public function setFromName(string $fromName): void
72    {
73        $this->fromName = $fromName;
74    }
75}