OrganizationCreationHandler.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Message\Handler;
  4. use App\Message\Message\OrganizationCreation;
  5. use App\Service\Organization\OrganizationFactory;
  6. use Symfony\Component\Mailer\MailerInterface;
  7. use Symfony\Component\Messenger\Attribute\AsMessageHandler;
  8. use Symfony\Component\Mime\Address;
  9. use Symfony\Component\Mime\Email as SymfonyEmail;
  10. use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
  11. #[AsMessageHandler(priority: 1)]
  12. class OrganizationCreationHandler
  13. {
  14. public function __construct(
  15. private readonly OrganizationFactory $organizationFactory,
  16. private readonly MailerInterface $symfonyMailer,
  17. ) {
  18. }
  19. /**
  20. * @throws \Throwable
  21. * @throws TransportExceptionInterface
  22. * @throws \Symfony\Component\Mailer\Exception\TransportExceptionInterface
  23. */
  24. public function __invoke(OrganizationCreation $organizationCreationCommand): void
  25. {
  26. $organizationCreationRequest = $organizationCreationCommand->getOrganizationCreationRequest();
  27. $mail = ['subject' => '', 'content' => ''];
  28. try {
  29. $organization = $this->organizationFactory->create($organizationCreationRequest);
  30. $mail['subject'] = 'New organization created';
  31. $mail['content'] = 'The organization "'.$organization->getName().'" has been created successfully.';
  32. } catch (\Exception $e) {
  33. $mail['subject'] = 'Organization creation : an error occured';
  34. $mail['content'] = 'An error occured while creating the new organization : \n'.$e->getMessage();
  35. throw $e;
  36. } finally {
  37. if ($organizationCreationRequest->getSendConfirmationEmailAt() !== null) {
  38. $symfonyMail = (new SymfonyEmail())
  39. ->from('mail.report@opentalent.fr')
  40. ->replyTo('mail.report@opentalent.fr')
  41. ->returnPath(Address::create('mail.report@opentalent.fr'))
  42. ->to($organizationCreationRequest->getSendConfirmationEmailAt())
  43. ->subject($mail['subject'])
  44. ->text($mail['content']);
  45. $this->symfonyMailer->send($symfonyMail);
  46. }
  47. }
  48. }
  49. }