AbstractTransport.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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\Notifier\Transport;
  11. use Symfony\Component\EventDispatcher\Event;
  12. use Symfony\Component\EventDispatcher\LegacyEventDispatcherProxy;
  13. use Symfony\Component\HttpClient\HttpClient;
  14. use Symfony\Component\Notifier\Event\MessageEvent;
  15. use Symfony\Component\Notifier\Exception\LogicException;
  16. use Symfony\Component\Notifier\Message\MessageInterface;
  17. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  18. use Symfony\Contracts\HttpClient\HttpClientInterface;
  19. /**
  20. * @author Fabien Potencier <fabien@symfony.com>
  21. *
  22. * @experimental in 5.1
  23. */
  24. abstract class AbstractTransport implements TransportInterface
  25. {
  26. protected const HOST = 'localhost';
  27. private $dispatcher;
  28. protected $client;
  29. protected $host;
  30. protected $port;
  31. public function __construct(HttpClientInterface $client = null, EventDispatcherInterface $dispatcher = null)
  32. {
  33. $this->client = $client;
  34. if (null === $client) {
  35. if (!class_exists(HttpClient::class)) {
  36. throw new LogicException(sprintf('You cannot use "%s" as the HttpClient component is not installed. Try running "composer require symfony/http-client".', __CLASS__));
  37. }
  38. $this->client = HttpClient::create();
  39. }
  40. $this->dispatcher = class_exists(Event::class) ? LegacyEventDispatcherProxy::decorate($dispatcher) : $dispatcher;
  41. }
  42. /**
  43. * @return $this
  44. */
  45. public function setHost(?string $host): self
  46. {
  47. $this->host = $host;
  48. return $this;
  49. }
  50. /**
  51. * @return $this
  52. */
  53. public function setPort(?int $port): self
  54. {
  55. $this->port = $port;
  56. return $this;
  57. }
  58. public function send(MessageInterface $message): void
  59. {
  60. if (null !== $this->dispatcher) {
  61. $this->dispatcher->dispatch(new MessageEvent($message));
  62. }
  63. $this->doSend($message);
  64. }
  65. abstract protected function doSend(MessageInterface $message): void;
  66. protected function getEndpoint(): ?string
  67. {
  68. return ($this->host ?: $this->getDefaultHost()).($this->port ? ':'.$this->port : '');
  69. }
  70. protected function getDefaultHost(): string
  71. {
  72. return static::HOST;
  73. }
  74. }