vendor/bornfreee/tactician-domain-events/src/Middleware/ReleaseRecordedEventsMiddleware.php line 46

Open in your IDE?
  1. <?php
  2. namespace BornFree\TacticianDomainEvent\Middleware;
  3. use BornFree\TacticianDomainEvent\EventDispatcher\EventDispatcherInterface;
  4. use BornFree\TacticianDomainEvent\Recorder\ContainsRecordedEvents;
  5. use League\Tactician\Middleware;
  6. class ReleaseRecordedEventsMiddleware implements Middleware
  7. {
  8. /**
  9. * @var ContainsRecordedEvents
  10. */
  11. private $eventRecorder;
  12. /**
  13. * @var EventDispatcherInterface
  14. */
  15. private $eventDispatcher;
  16. /**
  17. * ReleaseRecorderEventsMiddleware constructor.
  18. *
  19. * @param ContainsRecordedEvents $eventRecorder
  20. * @param EventDispatcherInterface $eventDispatcher
  21. */
  22. public function __construct(ContainsRecordedEvents $eventRecorder, EventDispatcherInterface $eventDispatcher)
  23. {
  24. $this->eventRecorder = $eventRecorder;
  25. $this->eventDispatcher = $eventDispatcher;
  26. }
  27. /**
  28. * Dispatches all the recorded events in the EventBus and erases them
  29. *
  30. * @param object $command
  31. * @param callable $next
  32. *
  33. * @return mixed
  34. *
  35. * @throws \Exception
  36. */
  37. public function execute($command, callable $next)
  38. {
  39. try {
  40. $result = $next($command);
  41. } catch (\Exception $exception) {
  42. $this->eventRecorder->eraseEvents();
  43. throw $exception;
  44. }
  45. $recordedEvents = $this->eventRecorder->releaseEvents();
  46. foreach ($recordedEvents as $event) {
  47. $this->eventDispatcher->dispatch($event);
  48. }
  49. return $result;
  50. }
  51. }