CircularDependencyDetection::acquire()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 1
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Habemus;
5
6
use Closure;
7
use Habemus\Exception\CircularDependencyException;
8
9
class CircularDependencyDetection
10
{
11
    /**
12
     * @var array
13
     */
14
    protected $executing = [];
15
16
    /**
17
     * @param mixed $id
18
     * @param Closure $process
19
     * @return mixed
20
     * @throws CircularDependencyException
21
     */
22
    public function execute($id, Closure $process)
23
    {
24
        if ($this->isExecuting($id)) {
25
            throw CircularDependencyException::forId($id, array_keys($this->executing));
26
        }
27
28
        $this->acquire($id);
29
30
        try {
31
            return $process();
32
        } finally {
33
            $this->release($id);
34
        }
35
    }
36
37
    protected function acquire($id): void
38
    {
39
        $this->executing[$id] = true;
40
    }
41
42
    protected function release($id): void
43
    {
44
        unset($this->executing[$id]);
45
    }
46
47
    public function isExecuting($id): bool
48
    {
49
        return array_key_exists($id, $this->executing);
50
    }
51
}
52