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