LockingMiddleware   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 62
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 62
ccs 17
cts 17
cp 1
rs 10
c 0
b 0
f 0

2 Methods

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