|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace App\Command; |
| 6 | + |
| 7 | +use App\Notifications\CommandExecuted; |
| 8 | +use Ibexa\Contracts\Core\Repository\UserService; |
| 9 | +use Ibexa\Contracts\Notifications\Service\NotificationServiceInterface; |
| 10 | +use Ibexa\Contracts\Notifications\Value\Notification\SymfonyNotificationAdapter; |
| 11 | +use Ibexa\Contracts\Notifications\Value\Recipent\SymfonyRecipientAdapter; |
| 12 | +use Ibexa\Contracts\Notifications\Value\Recipent\UserRecipient; |
| 13 | +use Symfony\Component\Console\Attribute\AsCommand; |
| 14 | +use Symfony\Component\Console\Command\Command; |
| 15 | +use Symfony\Component\Console\Input\InputInterface; |
| 16 | +use Symfony\Component\Console\Output\OutputInterface; |
| 17 | +use Symfony\Component\Notifier\Recipient\RecipientInterface; |
| 18 | + |
| 19 | +#[AsCommand(name: 'app:send_notification', description: 'Example of command sending a notification')] |
| 20 | +class NotificationSenderCommand extends Command |
| 21 | +{ |
| 22 | + /** @param array<int, string> $recipientLogins */ |
| 23 | + public function __construct( |
| 24 | + private readonly NotificationServiceInterface $notificationService, |
| 25 | + private readonly UserService $userService, |
| 26 | + private readonly array $recipientLogins = ['admin'], |
| 27 | + ) { |
| 28 | + parent::__construct(); |
| 29 | + } |
| 30 | + |
| 31 | + protected function execute(InputInterface $input, OutputInterface $output): int |
| 32 | + { |
| 33 | + /** @var array<int, \Throwable> $exceptions */ |
| 34 | + $exceptions = []; |
| 35 | + |
| 36 | + try { |
| 37 | + // Do something |
| 38 | + if (random_int(0, 1) == 1) { |
| 39 | + throw new \RuntimeException('Something went wrong'); |
| 40 | + } |
| 41 | + $exitCode = Command::SUCCESS; |
| 42 | + } catch (\Exception $exception) { |
| 43 | + $exceptions[] = $exception; |
| 44 | + $exitCode = Command::FAILURE; |
| 45 | + } |
| 46 | + |
| 47 | + $recipients = []; |
| 48 | + foreach ($this->recipientLogins as $login) { |
| 49 | + try { |
| 50 | + $user = $this->userService->loadUserByLogin($login); |
| 51 | + $recipients[] = new UserRecipient($user); |
| 52 | + } catch (\Exception $exception) { |
| 53 | + $exceptions[] = $exception; |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + $this->notificationService->send( |
| 58 | + new SymfonyNotificationAdapter(new CommandExecuted($this, $exitCode, $exceptions)), |
| 59 | + array_map( |
| 60 | + static fn (RecipientInterface $recipient): SymfonyRecipientAdapter => new SymfonyRecipientAdapter($recipient), |
| 61 | + $recipients |
| 62 | + ) |
| 63 | + ); |
| 64 | + |
| 65 | + return $exitCode; |
| 66 | + } |
| 67 | +} |
0 commit comments