Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
92.31% |
12 / 13 |
|
50.00% |
1 / 2 |
CRAP | |
0.00% |
0 / 1 |
| Delivery | |
92.31% |
12 / 13 |
|
50.00% |
1 / 2 |
6.02 | |
0.00% |
0 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| handle | |
91.67% |
11 / 12 |
|
0.00% |
0 / 1 |
5.01 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Cosray\Mail; |
| 6 | |
| 7 | use Cosray\Contract\Job; |
| 8 | use Cosray\Exception\JobFailed; |
| 9 | use Override; |
| 10 | use Psr\Log\LoggerInterface as Logger; |
| 11 | use Symfony\Component\Mime\Exception\RfcComplianceException; |
| 12 | use Throwable; |
| 13 | |
| 14 | /** |
| 15 | * Sends one queued mail. A transport error fails the attempt, so the |
| 16 | * queue tries again later; a mail that cannot be read or addressed, or |
| 17 | * whose transport is no longer configured, fails at once. |
| 18 | * |
| 19 | * @internal |
| 20 | */ |
| 21 | final class Delivery implements Job |
| 22 | { |
| 23 | public function __construct( |
| 24 | private readonly Transports $transports, |
| 25 | private readonly Logger $logger, |
| 26 | ) {} |
| 27 | |
| 28 | #[Override] |
| 29 | public function handle(array $payload): void |
| 30 | { |
| 31 | try { |
| 32 | [$email, $transport] = Payload::decode($payload); |
| 33 | } catch (Throwable $e) { |
| 34 | throw new JobFailed("The queued mail cannot be read: {$e->getMessage()}", previous: $e); |
| 35 | } |
| 36 | |
| 37 | if ($transport !== null && !$this->transports->has($transport)) { |
| 38 | throw new JobFailed("There is no mail transport named {$transport}."); |
| 39 | } |
| 40 | |
| 41 | try { |
| 42 | $this->transports->send($email, $transport); |
| 43 | } catch (RfcComplianceException $e) { |
| 44 | throw new JobFailed($e->getMessage(), previous: $e); |
| 45 | } |
| 46 | |
| 47 | $this->logger->info('Mail sent to {count} recipients through {transport}', [ |
| 48 | 'count' => count($email->getTo()) + count($email->getCc()) + count($email->getBcc()), |
| 49 | 'transport' => $transport ?? 'the default transport', |
| 50 | ]); |
| 51 | } |
| 52 | } |