LockingMiddleware::execute()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 12
cts 12
cp 1
rs 9.552
c 0
b 0
f 0
cc 3
nc 3
nop 2
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Lamoda\TacticianLockingMiddleware;
6
7
use League\Tactician\Middleware;
8
9
/**
10
 * If another command is already being executed, locks the command bus and
11
 * queues the new incoming commands until the first has completed.
12
 */
13
class LockingMiddleware implements Middleware
14
{
15
    /**
16
     * @var bool
17
     */
18
    private $isExecuting;
19
20
    /**
21
     * @var callable[]
22
     */
23
    private $queue = [];
24
25
    /**
26
     * This middleware differs from the original in a way it handles Throwable, not only Exception.
27
     *
28
     * @param object   $command
29
     * @param callable $next
30
     *
31
     * @throws \Throwable
32
     *
33
     * @return mixed|void
34
     */
35 3
    public function execute($command, callable $next)
36
    {
37
        $this->queue[] = static function () use ($command, $next) {
38 3
            return $next($command);
39
        };
40
41 3
        if ($this->isExecuting) {
42 1
            return;
43
        }
44 3
        $this->isExecuting = true;
45
46
        try {
47 3
            $returnValue = $this->executeQueuedJobs();
48 1
        } catch (\Throwable $e) {
49 1
            $this->isExecuting = false;
50 1
            $this->queue = [];
51 1
            throw $e;
52
        }
53
54 3
        $this->isExecuting = false;
55
56 3
        return $returnValue;
57
    }
58
59
    /**
60
     * Process any pending commands in the queue. If multiple, jobs are in the
61
     * queue, only the first return value is given back.
62
     *
63
     * @return mixed
64
     */
65 3
    protected function executeQueuedJobs()
66
    {
67 3
        $returnValues = [];
68 3
        while ($resumeCommand = array_shift($this->queue)) {
69 3
            $returnValues[] = $resumeCommand();
70
        }
71
72 3
        return array_shift($returnValues);
73
    }
74
}
75