DoctrineSender.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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\Messenger\Bridge\Doctrine\Transport;
  11. use Doctrine\DBAL\DBALException;
  12. use Doctrine\DBAL\Exception;
  13. use Symfony\Component\Messenger\Envelope;
  14. use Symfony\Component\Messenger\Exception\TransportException;
  15. use Symfony\Component\Messenger\Stamp\DelayStamp;
  16. use Symfony\Component\Messenger\Stamp\TransportMessageIdStamp;
  17. use Symfony\Component\Messenger\Transport\Sender\SenderInterface;
  18. use Symfony\Component\Messenger\Transport\Serialization\PhpSerializer;
  19. use Symfony\Component\Messenger\Transport\Serialization\SerializerInterface;
  20. /**
  21. * @author Vincent Touzet <vincent.touzet@gmail.com>
  22. */
  23. class DoctrineSender implements SenderInterface
  24. {
  25. private $connection;
  26. private $serializer;
  27. public function __construct(Connection $connection, SerializerInterface $serializer = null)
  28. {
  29. $this->connection = $connection;
  30. $this->serializer = $serializer ?? new PhpSerializer();
  31. }
  32. /**
  33. * {@inheritdoc}
  34. */
  35. public function send(Envelope $envelope): Envelope
  36. {
  37. $encodedMessage = $this->serializer->encode($envelope);
  38. /** @var DelayStamp|null $delayStamp */
  39. $delayStamp = $envelope->last(DelayStamp::class);
  40. $delay = null !== $delayStamp ? $delayStamp->getDelay() : 0;
  41. try {
  42. $id = $this->connection->send($encodedMessage['body'], $encodedMessage['headers'] ?? [], $delay);
  43. } catch (DBALException | Exception $exception) {
  44. throw new TransportException($exception->getMessage(), 0, $exception);
  45. }
  46. return $envelope->with(new TransportMessageIdStamp($id));
  47. }
  48. }
  49. class_alias(DoctrineSender::class, \Symfony\Component\Messenger\Transport\Doctrine\DoctrineSender::class);