LockingMiddleware   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 0
dl 0
loc 61
ccs 17
cts 17
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A executeQueuedJobs() 0 9 2
A execute() 0 22 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