DoctrineCloseConnectionMiddleware.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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\Middleware\StackInterface;
  14. use Symfony\Component\Messenger\Stamp\ConsumedByWorkerStamp;
  15. /**
  16. * Closes connection and therefore saves number of connections.
  17. *
  18. * @author Fuong <insidestyles@gmail.com>
  19. */
  20. class DoctrineCloseConnectionMiddleware extends AbstractDoctrineMiddleware
  21. {
  22. protected function handleForManager(EntityManagerInterface $entityManager, Envelope $envelope, StackInterface $stack): Envelope
  23. {
  24. try {
  25. $connection = $entityManager->getConnection();
  26. return $stack->next()->handle($envelope, $stack);
  27. } finally {
  28. if (null !== $envelope->last(ConsumedByWorkerStamp::class)) {
  29. $connection->close();
  30. }
  31. }
  32. }
  33. }