DoctrineTransactionMiddleware.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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\Bridge\Doctrine\Messenger;
  11. use Doctrine\ORM\EntityManagerInterface;
  12. use Symfony\Component\Messenger\Envelope;
  13. use Symfony\Component\Messenger\Exception\HandlerFailedException;
  14. use Symfony\Component\Messenger\Middleware\StackInterface;
  15. use Symfony\Component\Messenger\Stamp\HandledStamp;
  16. /**
  17. * Wraps all handlers in a single doctrine transaction.
  18. *
  19. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  20. */
  21. class DoctrineTransactionMiddleware extends AbstractDoctrineMiddleware
  22. {
  23. protected function handleForManager(EntityManagerInterface $entityManager, Envelope $envelope, StackInterface $stack): Envelope
  24. {
  25. $entityManager->getConnection()->beginTransaction();
  26. try {
  27. $envelope = $stack->next()->handle($envelope, $stack);
  28. $entityManager->flush();
  29. $entityManager->getConnection()->commit();
  30. return $envelope;
  31. } catch (\Throwable $exception) {
  32. $entityManager->getConnection()->rollBack();
  33. if ($exception instanceof HandlerFailedException) {
  34. // Remove all HandledStamp from the envelope so the retry will execute all handlers again.
  35. // When a handler fails, the queries of allegedly successful previous handlers just got rolled back.
  36. throw new HandlerFailedException($exception->getEnvelope()->withoutAll(HandledStamp::class), $exception->getNestedExceptions());
  37. }
  38. throw $exception;
  39. }
  40. }
  41. }