vendor/symfony/doctrine-bridge/Messenger/DoctrineClearEntityManagerWorkerSubscriber.php line 38

  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\Persistence\ManagerRegistry;
  12. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  13. use Symfony\Component\Messenger\Event\WorkerMessageFailedEvent;
  14. use Symfony\Component\Messenger\Event\WorkerMessageHandledEvent;
  15. /**
  16.  * Clears entity managers between messages being handled to avoid outdated data.
  17.  *
  18.  * @author Ryan Weaver <ryan@symfonycasts.com>
  19.  */
  20. class DoctrineClearEntityManagerWorkerSubscriber implements EventSubscriberInterface
  21. {
  22.     public function __construct(
  23.         private readonly ManagerRegistry $managerRegistry,
  24.     ) {
  25.     }
  26.     /**
  27.      * @return void
  28.      */
  29.     public function onWorkerMessageHandled()
  30.     {
  31.         $this->clearEntityManagers();
  32.     }
  33.     /**
  34.      * @return void
  35.      */
  36.     public function onWorkerMessageFailed()
  37.     {
  38.         $this->clearEntityManagers();
  39.     }
  40.     public static function getSubscribedEvents(): array
  41.     {
  42.         return [
  43.             WorkerMessageHandledEvent::class => 'onWorkerMessageHandled',
  44.             WorkerMessageFailedEvent::class => 'onWorkerMessageFailed',
  45.         ];
  46.     }
  47.     private function clearEntityManagers(): void
  48.     {
  49.         foreach ($this->managerRegistry->getManagers() as $manager) {
  50.             $manager->clear();
  51.         }
  52.     }
  53. }