DoctrinePingConnectionMiddleware.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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\DBAL\DBALException;
  12. use Doctrine\DBAL\Exception;
  13. use Doctrine\ORM\EntityManagerInterface;
  14. use Symfony\Component\Messenger\Envelope;
  15. use Symfony\Component\Messenger\Middleware\StackInterface;
  16. use Symfony\Component\Messenger\Stamp\ConsumedByWorkerStamp;
  17. /**
  18. * Checks whether the connection is still open or reconnects otherwise.
  19. *
  20. * @author Fuong <insidestyles@gmail.com>
  21. */
  22. class DoctrinePingConnectionMiddleware extends AbstractDoctrineMiddleware
  23. {
  24. protected function handleForManager(EntityManagerInterface $entityManager, Envelope $envelope, StackInterface $stack): Envelope
  25. {
  26. if (null !== $envelope->last(ConsumedByWorkerStamp::class)) {
  27. $this->pingConnection($entityManager);
  28. }
  29. return $stack->next()->handle($envelope, $stack);
  30. }
  31. private function pingConnection(EntityManagerInterface $entityManager)
  32. {
  33. $connection = $entityManager->getConnection();
  34. try {
  35. $connection->executeQuery($connection->getDatabasePlatform()->getDummySelectSQL());
  36. } catch (DBALException | Exception $e) {
  37. $connection->close();
  38. $connection->connect();
  39. }
  40. if (!$entityManager->isOpen()) {
  41. $this->managerRegistry->resetManager($this->entityManagerName);
  42. }
  43. }
  44. }