Mailer.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Mailer;
  11. use Symfony\Component\EventDispatcher\Event;
  12. use Symfony\Component\EventDispatcher\LegacyEventDispatcherProxy;
  13. use Symfony\Component\Mailer\Event\MessageEvent;
  14. use Symfony\Component\Mailer\Messenger\SendEmailMessage;
  15. use Symfony\Component\Mailer\Transport\TransportInterface;
  16. use Symfony\Component\Messenger\MessageBusInterface;
  17. use Symfony\Component\Mime\RawMessage;
  18. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  19. /**
  20. * @author Fabien Potencier <fabien@symfony.com>
  21. */
  22. final class Mailer implements MailerInterface
  23. {
  24. private $transport;
  25. private $bus;
  26. private $dispatcher;
  27. public function __construct(TransportInterface $transport, MessageBusInterface $bus = null, EventDispatcherInterface $dispatcher = null)
  28. {
  29. $this->transport = $transport;
  30. $this->bus = $bus;
  31. $this->dispatcher = class_exists(Event::class) ? LegacyEventDispatcherProxy::decorate($dispatcher) : $dispatcher;
  32. }
  33. public function send(RawMessage $message, Envelope $envelope = null): void
  34. {
  35. if (null === $this->bus) {
  36. $this->transport->send($message, $envelope);
  37. return;
  38. }
  39. if (null !== $this->dispatcher) {
  40. $clonedMessage = clone $message;
  41. $clonedEnvelope = null !== $envelope ? clone $envelope : Envelope::create($clonedMessage);
  42. $event = new MessageEvent($clonedMessage, $clonedEnvelope, (string) $this->transport, true);
  43. $this->dispatcher->dispatch($event);
  44. }
  45. $this->bus->dispatch(new SendEmailMessage($message, $envelope));
  46. }
  47. }