AbstractHttpTransport.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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\Transport;
  11. use Psr\EventDispatcher\EventDispatcherInterface;
  12. use Psr\Log\LoggerInterface;
  13. use Symfony\Component\HttpClient\HttpClient;
  14. use Symfony\Component\Mailer\Exception\HttpTransportException;
  15. use Symfony\Component\Mailer\SentMessage;
  16. use Symfony\Contracts\HttpClient\HttpClientInterface;
  17. use Symfony\Contracts\HttpClient\ResponseInterface;
  18. /**
  19. * @author Victor Bocharsky <victor@symfonycasts.com>
  20. */
  21. abstract class AbstractHttpTransport extends AbstractTransport
  22. {
  23. protected ?string $host = null;
  24. protected ?int $port = null;
  25. public function __construct(
  26. protected ?HttpClientInterface $client = null,
  27. ?EventDispatcherInterface $dispatcher = null,
  28. ?LoggerInterface $logger = null,
  29. ) {
  30. if (null === $client) {
  31. if (!class_exists(HttpClient::class)) {
  32. throw new \LogicException(\sprintf('You cannot use "%s" as the HttpClient component is not installed. Try running "composer require symfony/http-client".', __CLASS__));
  33. }
  34. $this->client = HttpClient::create();
  35. }
  36. parent::__construct($dispatcher, $logger);
  37. }
  38. /**
  39. * @return $this
  40. */
  41. public function setHost(?string $host): static
  42. {
  43. $this->host = $host;
  44. return $this;
  45. }
  46. /**
  47. * @return $this
  48. */
  49. public function setPort(?int $port): static
  50. {
  51. $this->port = $port;
  52. return $this;
  53. }
  54. abstract protected function doSendHttp(SentMessage $message): ResponseInterface;
  55. protected function doSend(SentMessage $message): void
  56. {
  57. try {
  58. $response = $this->doSendHttp($message);
  59. $message->appendDebug($response->getInfo('debug') ?? '');
  60. } catch (HttpTransportException $e) {
  61. $e->appendDebug($e->getResponse()->getInfo('debug') ?? '');
  62. throw $e;
  63. }
  64. }
  65. }