1 | <?php |
||
12 | class LockingMiddleware implements Middleware |
||
13 | { |
||
14 | /** |
||
15 | * @var bool |
||
16 | */ |
||
17 | private $isExecuting; |
||
18 | |||
19 | /** |
||
20 | * @var callable[] |
||
21 | */ |
||
22 | private $queue = []; |
||
23 | |||
24 | /** |
||
25 | * Execute the given command... after other running commands are complete. |
||
26 | * |
||
27 | * @param object $command |
||
28 | * @param callable $next |
||
29 | * |
||
30 | * @throws Throwable |
||
31 | * |
||
32 | * @return mixed|void |
||
33 | */ |
||
34 | 8 | public function execute($command, callable $next) |
|
35 | { |
||
36 | $this->queue[] = static function () use ($command, $next) { |
||
37 | 8 | return $next($command); |
|
38 | }; |
||
39 | |||
40 | 8 | if ($this->isExecuting) { |
|
41 | 4 | return; |
|
42 | } |
||
43 | 8 | $this->isExecuting = true; |
|
44 | |||
45 | try { |
||
46 | 8 | $returnValue = $this->executeQueuedJobs(); |
|
47 | 3 | } catch (Throwable $e) { |
|
48 | 3 | $this->isExecuting = false; |
|
49 | 3 | $this->queue = []; |
|
50 | 3 | throw $e; |
|
51 | } |
||
52 | |||
53 | 7 | $this->isExecuting = false; |
|
54 | 7 | return $returnValue; |
|
55 | } |
||
56 | |||
57 | /** |
||
58 | * Process any pending commands in the queue. If multiple, jobs are in the |
||
59 | * queue, only the first return value is given back. |
||
60 | * |
||
61 | * @return mixed |
||
62 | */ |
||
63 | 8 | protected function executeQueuedJobs() |
|
72 | } |
||
73 |