Passed
Push — master ( bf075b...6deca2 )
by Petr
07:21
created

SemaphoreLock   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 26
c 1
b 0
f 0
dl 0
loc 61
ccs 26
cts 26
cp 1
rs 10
wmc 14

6 Methods

Rating   Name   Duplication   Size   Complexity  
A delete() 0 9 4
A __construct() 0 4 1
A __destruct() 0 5 2
A has() 0 6 2
A create() 0 9 4
A setKey() 0 2 1
1
<?php
2
3
namespace kalanis\kw_locks\Methods;
4
5
6
use kalanis\kw_locks\Interfaces\IKLTranslations;
7
use kalanis\kw_locks\Interfaces\IPassedKey;
8
use kalanis\kw_locks\LockException;
9
use kalanis\kw_locks\Traits\TLang;
10
use kalanis\kw_semaphore\Interfaces\ISemaphore;
11
use kalanis\kw_semaphore\SemaphoreException;
12
13
14
/**
15
 * Class SemaphoreLock
16
 * @package kalanis\kw_locks\Methods
17
 */
18
class SemaphoreLock implements IPassedKey
19
{
20
    use TLang;
21
22
    /** @var ISemaphore */
23
    protected $semaphore = null;
24
    /** @var string[] */
25
    protected $specialKey = [];
26
    /** @var string */
27
    protected $checkContent = '';
28
29 4
    public function __construct(ISemaphore $semaphore, ?IKLTranslations $lang = null)
30
    {
31 4
        $this->semaphore = $semaphore;
32 4
        $this->setKlLang($lang);
33 4
    }
34
35 4
    public function __destruct()
36
    {
37
        try {
38 4
            $this->delete();
39 3
        } catch (LockException $ex) {
40
            // do nothing instead of
41
            // register_shutdown_function([$this, 'delete']);
42
        }
43 4
    }
44
45 4
    public function setKey(string $key, string $checkContent = ''): void
46
    {
47 4
    }
48
49 4
    public function has(): bool
50
    {
51
        try {
52 4
            return $this->semaphore->has();
53 3
        } catch (SemaphoreException $ex) {
54 3
            throw new LockException($this->getKlLang()->iklProblemWithStorage(), $ex->getCode(), $ex);
55
        }
56
    }
57
58 2
    public function create(bool $force = false): bool
59
    {
60 2
        if (!$force && $this->has()) {
61 1
            return false;
62
        }
63
        try {
64 2
            return $this->semaphore->want();
65 1
        } catch (SemaphoreException $ex) {
66 1
            throw new LockException($this->getKlLang()->iklProblemWithStorage(), $ex->getCode(), $ex);
67
        }
68
    }
69
70 4
    public function delete(bool $force = false): bool
71
    {
72 4
        if (!$force && !$this->has()) {
73 1
            return true;
74
        }
75
        try {
76 2
            return $this->semaphore->remove();
77 1
        } catch (SemaphoreException $ex) {
78 1
            throw new LockException($this->getKlLang()->iklProblemWithStorage(), $ex->getCode(), $ex);
79
        }
80
    }
81
}
82