2025-09-24 06:24:52 +00:00
< ? php
/*
* This file is part of the Symfony package .
*
* ( c ) Fabien Potencier < fabien @ symfony . com >
*
* For the full copyright and license information , please view the LICENSE
* file that was distributed with this source code .
*/
namespace Symfony\Component\Mailer\Transport ;
use Symfony\Component\Mailer\Envelope ;
use Symfony\Component\Mailer\Exception\InvalidArgumentException ;
use Symfony\Component\Mailer\Exception\LogicException ;
use Symfony\Component\Mailer\SentMessage ;
use Symfony\Component\Mime\Message ;
use Symfony\Component\Mime\RawMessage ;
/**
* @ author Fabien Potencier < fabien @ symfony . com >
*/
final class Transports implements TransportInterface
{
2025-10-03 11:00:05 +00:00
private $transports ;
private $default ;
2025-09-24 06:24:52 +00:00
/**
2025-10-03 11:00:05 +00:00
* @ param TransportInterface [] $transports
2025-09-24 06:24:52 +00:00
*/
public function __construct ( iterable $transports )
{
2025-10-03 11:00:05 +00:00
$this -> transports = [];
2025-09-24 06:24:52 +00:00
foreach ( $transports as $name => $transport ) {
2025-10-03 11:00:05 +00:00
if ( null === $this -> default ) {
$this -> default = $transport ;
}
2025-09-24 06:24:52 +00:00
$this -> transports [ $name ] = $transport ;
}
if ( ! $this -> transports ) {
2025-10-03 11:00:05 +00:00
throw new LogicException ( sprintf ( '"%s" must have at least one transport configured.' , __CLASS__ ));
2025-09-24 06:24:52 +00:00
}
}
public function send ( RawMessage $message , ? Envelope $envelope = null ) : ? SentMessage
{
/** @var Message $message */
2025-10-03 11:00:05 +00:00
if ( RawMessage :: class === \get_class ( $message ) || ! $message -> getHeaders () -> has ( 'X-Transport' )) {
2025-09-24 06:24:52 +00:00
return $this -> default -> send ( $message , $envelope );
}
$headers = $message -> getHeaders ();
$transport = $headers -> get ( 'X-Transport' ) -> getBody ();
$headers -> remove ( 'X-Transport' );
if ( ! isset ( $this -> transports [ $transport ])) {
2025-10-03 11:00:05 +00:00
throw new InvalidArgumentException ( sprintf ( 'The "%s" transport does not exist (available transports: "%s").' , $transport , implode ( '", "' , array_keys ( $this -> transports ))));
2025-09-24 06:24:52 +00:00
}
try {
return $this -> transports [ $transport ] -> send ( $message , $envelope );
} catch ( \Throwable $e ) {
$headers -> addTextHeader ( 'X-Transport' , $transport );
throw $e ;
}
}
public function __toString () : string
{
return '[' . implode ( ',' , array_keys ( $this -> transports )) . ']' ;
}
}