OrganizationDeletionHandler.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Message\Handler;
  4. use App\Message\Message\OrganizationDeletion;
  5. use App\Service\Organization\OrganizationFactory;
  6. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  7. use Symfony\Component\Mailer\MailerInterface;
  8. use Symfony\Component\Messenger\Attribute\AsMessageHandler;
  9. use Symfony\Component\Mime\Address;
  10. use Symfony\Component\Mime\Email as SymfonyEmail;
  11. #[AsMessageHandler(priority: 1)]
  12. readonly class OrganizationDeletionHandler
  13. {
  14. public function __construct(
  15. private OrganizationFactory $organizationFactory,
  16. private MailerInterface $symfonyMailer,
  17. private string $opentalentMailReport,
  18. ) {
  19. }
  20. /**
  21. * @throws \Throwable
  22. * @throws TransportExceptionInterface
  23. */
  24. public function __invoke(OrganizationDeletion $organizationDeletionCommand): void
  25. {
  26. $organizationCreationRequest = $organizationDeletionCommand->getOrganizationDeletionRequest();
  27. try {
  28. $this->organizationFactory->delete($organizationCreationRequest);
  29. $this->sendMail(
  30. $organizationCreationRequest->getSendConfirmationEmailAt() ?? $this->opentalentMailReport,
  31. 'Organization deleted',
  32. 'The organization n° '.$organizationCreationRequest->getOrganizationId().' has been deleted successfully.',
  33. );
  34. } catch (\Exception $e) {
  35. $this->sendMail(
  36. $organizationCreationRequest->getSendConfirmationEmailAt() ?? $this->opentalentMailReport,
  37. 'Organization deletion : an error occurred',
  38. 'An error occurred while deleting the new organization : \n'.$e->getMessage()
  39. );
  40. throw $e;
  41. }
  42. }
  43. /**
  44. * @throws TransportExceptionInterface
  45. */
  46. private function sendMail(
  47. string $to,
  48. string $subject,
  49. string $content,
  50. ): void
  51. {
  52. $symfonyMail = (new SymfonyEmail())
  53. ->from($this->opentalentMailReport)
  54. ->replyTo($this->opentalentMailReport)
  55. ->returnPath(Address::create($this->opentalentMailReport))
  56. ->to($to)
  57. ->subject($subject)
  58. ->text($content);
  59. $this->symfonyMailer->send($symfonyMail);
  60. }
  61. }