LockingMiddleware::execute()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 12
cts 12
cp 1
rs 9.568
c 0
b 0
f 0
cc 3
nc 3
nop 2
crap 3
1
<?php
2
3
namespace League\Tactician\Plugins;
4
5
use League\Tactician\Middleware;
6
use Throwable;
7
8
/**
9
 * If another command is already being executed, locks the command bus and
10
 * queues the new incoming commands until the first has completed.
11
 */
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()
64
    {
65 8
        $returnValues = [];
66 8
        while ($resumeCommand = array_shift($this->queue)) {
67 8
            $returnValues[] = $resumeCommand();
68
        }
69
70 7
        return array_shift($returnValues);
71
    }
72
}
73