vendor/league/tactician/src/Plugins/LockingMiddleware.php line 66

Open in your IDE?
  1. <?php
  2. namespace League\Tactician\Plugins;
  3. use League\Tactician\Middleware;
  4. /**
  5. * If another command is already being executed, locks the command bus and
  6. * queues the new incoming commands until the first has completed.
  7. */
  8. class LockingMiddleware implements Middleware
  9. {
  10. /**
  11. * @var bool
  12. */
  13. private $isExecuting;
  14. /**
  15. * @var callable[]
  16. */
  17. private $queue = [];
  18. /**
  19. * Execute the given command... after other running commands are complete.
  20. *
  21. * @param object $command
  22. * @param callable $next
  23. *
  24. * @throws \Exception
  25. *
  26. * @return mixed|void
  27. */
  28. public function execute($command, callable $next)
  29. {
  30. $this->queue[] = function () use ($command, $next) {
  31. return $next($command);
  32. };
  33. if ($this->isExecuting) {
  34. return;
  35. }
  36. $this->isExecuting = true;
  37. try {
  38. $returnValue = $this->executeQueuedJobs();
  39. } catch (\Exception $e) {
  40. $this->isExecuting = false;
  41. $this->queue = [];
  42. throw $e;
  43. }
  44. $this->isExecuting = false;
  45. return $returnValue;
  46. }
  47. /**
  48. * Process any pending commands in the queue. If multiple, jobs are in the
  49. * queue, only the first return value is given back.
  50. *
  51. * @return mixed
  52. */
  53. protected function executeQueuedJobs()
  54. {
  55. $returnValues = [];
  56. while ($resumeCommand = array_shift($this->queue)) {
  57. $returnValues[] = $resumeCommand();
  58. }
  59. return array_shift($returnValues);
  60. }
  61. }