DoctrineClearEntityManagerWorkerSubscriber.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. private $managerRegistry;
  23. public function __construct(ManagerRegistry $managerRegistry)
  24. {
  25. $this->managerRegistry = $managerRegistry;
  26. }
  27. public function onWorkerMessageHandled()
  28. {
  29. $this->clearEntityManagers();
  30. }
  31. public function onWorkerMessageFailed()
  32. {
  33. $this->clearEntityManagers();
  34. }
  35. public static function getSubscribedEvents()
  36. {
  37. yield WorkerMessageHandledEvent::class => 'onWorkerMessageHandled';
  38. yield WorkerMessageFailedEvent::class => 'onWorkerMessageFailed';
  39. }
  40. private function clearEntityManagers()
  41. {
  42. foreach ($this->managerRegistry->getManagers() as $manager) {
  43. $manager->clear();
  44. }
  45. }
  46. }