|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <fabien@symfony.com> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Symfony\Bridge\Doctrine\Messenger; |
| 13 | + |
| 14 | +use Doctrine\ORM\EntityManagerInterface; |
| 15 | +use Doctrine\Persistence\ManagerRegistry; |
| 16 | +use Psr\Log\LoggerInterface; |
| 17 | +use Psr\Log\NullLogger; |
| 18 | +use Symfony\Component\Messenger\Envelope; |
| 19 | +use Symfony\Component\Messenger\Middleware\StackInterface; |
| 20 | + |
| 21 | +/** |
| 22 | + * Search for open transactions, then log and close them. |
| 23 | + * |
| 24 | + * @author Grégoire Pineau <lyrixx@lyrixx.info> |
| 25 | + */ |
| 26 | +class DoctrineTransactionWatchdogMiddleware extends AbstractDoctrineMiddleware |
| 27 | +{ |
| 28 | + public function __construct(ManagerRegistry $managerRegistry, LoggerInterface $logger = null, string $entityManagerName = null) |
| 29 | + { |
| 30 | + parent::__construct($managerRegistry, $entityManagerName); |
| 31 | + |
| 32 | + $this->logger = $logger ?? new NullLogger(); |
| 33 | + } |
| 34 | + |
| 35 | + protected function handleForManager(EntityManagerInterface $entityManager, Envelope $envelope, StackInterface $stack): Envelope |
| 36 | + { |
| 37 | + try { |
| 38 | + return $stack->next()->handle($envelope, $stack); |
| 39 | + } finally { |
| 40 | + if ($entityManager->getConnection()->isTransactionActive()) { |
| 41 | + $this->logger->error('An handler open a transaction but did not close it.', [ |
| 42 | + 'message' => $envelope->getMessage(), |
| 43 | + ]); |
| 44 | + |
| 45 | + $connection = $entityManager->getConnection(); |
| 46 | + while ($connection->isTransactionActive()) { |
| 47 | + $connection->rollBack(); |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | +} |
0 commit comments