Code Coverage |
||||||||||||||||
Lines |
Branches |
Paths |
Functions and Methods |
Classes and Traits |
||||||||||||
| Total | |
100.00% |
10 / 10 |
|
93.33% |
14 / 15 |
|
30.00% |
3 / 10 |
|
66.67% |
2 / 3 |
CRAP | |
0.00% |
0 / 1 |
| NotificationDispatcher | |
100.00% |
10 / 10 |
|
93.33% |
14 / 15 |
|
30.00% |
3 / 10 |
|
100.00% |
3 / 3 |
29.95 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
75.00% |
3 / 4 |
|
50.00% |
1 / 2 |
|
100.00% |
1 / 1 |
2.50 | |||
| addSender | |
100.00% |
2 / 2 |
|
100.00% |
3 / 3 |
|
50.00% |
1 / 2 |
|
100.00% |
1 / 1 |
2.50 | |||
| dispatch | |
100.00% |
7 / 7 |
|
100.00% |
8 / 8 |
|
16.67% |
1 / 6 |
|
100.00% |
1 / 1 |
13.26 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace App\Service\Notification\Dispatcher; |
| 4 | |
| 5 | use App\Entity\Notification; |
| 6 | use App\Repository\NotificationLogRepositoryInterface; |
| 7 | use App\Service\Notification\Sender\NotificationSenderInterface; |
| 8 | use Symfony\Component\DependencyInjection\Attribute\AutowireIterator; |
| 9 | |
| 10 | /** |
| 11 | * @author Wilhelm Zwertvaegher |
| 12 | */ |
| 13 | class NotificationDispatcher implements NotificationDispatcherInterface |
| 14 | { |
| 15 | /** |
| 16 | * @var array<NotificationSenderInterface> |
| 17 | */ |
| 18 | private array $senders; |
| 19 | |
| 20 | /** |
| 21 | * @param iterable<NotificationSenderInterface> $senders |
| 22 | */ |
| 23 | public function __construct( |
| 24 | #[AutowireIterator('app.notification_sender')] |
| 25 | iterable $senders, |
| 26 | private readonly NotificationLogRepositoryInterface $notificationLogRepository, |
| 27 | ) { |
| 28 | $this->senders = is_array($senders) ? $senders : iterator_to_array($senders); |
| 29 | } |
| 30 | |
| 31 | public function addSender(NotificationSenderInterface $notificationSender): void |
| 32 | { |
| 33 | if (!array_any($this->senders, fn ($sender) => $sender->getName() === $notificationSender->getName())) { |
| 34 | $this->senders[] = $notificationSender; |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * @return array<NotificationDispatchResult> |
| 40 | */ |
| 41 | public function dispatch(Notification $notification): array |
| 42 | { |
| 43 | $results = []; |
| 44 | |
| 45 | foreach ($this->senders as $sender) { |
| 46 | if ($sender->supports($notification) |
| 47 | // avoid resending a notification which already succeeded |
| 48 | // this may be useful in case a notification previously partially failed, which could result in a global retry |
| 49 | && !$this->notificationLogRepository->hasSuccess($notification->getId(), $sender->getName()) |
| 50 | ) { |
| 51 | $senderResult = $sender->send($notification); |
| 52 | $results[] = new NotificationDispatchResult($sender->getName(), $senderResult->getStatus(), $senderResult->getMessage()); |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | return $results; |
| 57 | } |
| 58 | } |