vendor/league/tactician-doctrine/src/ORM/TransactionMiddleware.php line 41

Open in your IDE?
  1. <?php
  2. namespace League\Tactician\Doctrine\ORM;
  3. use Doctrine\ORM\EntityManagerInterface;
  4. use League\Tactician\Middleware;
  5. use Exception;
  6. use Throwable;
  7. /**
  8. * Wraps command execution inside a Doctrine ORM transaction
  9. */
  10. class TransactionMiddleware implements Middleware
  11. {
  12. /**
  13. * @var EntityManagerInterface
  14. */
  15. private $entityManager;
  16. /**
  17. * @param EntityManagerInterface $entityManager
  18. */
  19. public function __construct(EntityManagerInterface $entityManager)
  20. {
  21. $this->entityManager = $entityManager;
  22. }
  23. /**
  24. * Executes the given command and optionally returns a value
  25. *
  26. * @param object $command
  27. * @param callable $next
  28. * @return mixed
  29. * @throws Throwable
  30. * @throws Exception
  31. */
  32. public function execute($command, callable $next)
  33. {
  34. $this->entityManager->beginTransaction();
  35. try {
  36. $returnValue = $next($command);
  37. $this->entityManager->flush();
  38. $this->entityManager->commit();
  39. } catch (Exception $e) {
  40. $this->rollbackTransaction();
  41. throw $e;
  42. } catch (Throwable $e) {
  43. $this->rollbackTransaction();
  44. throw $e;
  45. }
  46. return $returnValue;
  47. }
  48. /**
  49. * Rollback the current transaction and close the entity manager when possible.
  50. */
  51. protected function rollbackTransaction()
  52. {
  53. $this->entityManager->rollback();
  54. $connection = $this->entityManager->getConnection();
  55. if (!$connection->isTransactionActive() || $connection->isRollbackOnly()) {
  56. $this->entityManager->close();
  57. }
  58. }
  59. }