Completed
Push — master ( 0ced52...d99b90 )
by Markus
03:30
created

LockTrait   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
eloc 17
dl 0
loc 59
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A release() 0 10 2
A acquire() 0 14 3
A createIdentifier() 0 5 1
1
<?php
2
3
namespace Jellyfish\Lock;
4
5
trait LockTrait
6
{
7
    /**
8
     * @var \Jellyfish\Lock\LockFactoryInterface
9
     */
10
    private $lockFactory;
11
12
    /**
13
     * @var \Jellyfish\Lock\LockInterface
14
     */
15
    private $lock;
16
17
    /**
18
     * @param string $identifier
19
     * @param float $ttl
20
     *
21
     * @return bool
22
     */
23
    private function acquire(string $identifier, float $ttl = 360.0): bool
24
    {
25
        if ($this->lockFactory === null) {
26
            return true;
27
        }
28
29
        $this->lock = $this->lockFactory->create($identifier, $ttl);
30
31
        if (!$this->lock->acquire()) {
32
            $this->lock = null;
33
            return false;
34
        }
35
36
        return true;
37
    }
38
39
    /**
40
     * @return \Jellyfish\Lock\LockTrait
41
     */
42
    private function release(): self
43
    {
44
        if ($this->lock === null) {
45
            return $this;
46
        }
47
48
        $this->lock->release();
49
        $this->lock = null;
50
51
        return $this;
52
    }
53
54
    /**
55
     * @param array $values
56
     *
57
     * @return string
58
     */
59
    private function createIdentifier(array $values): string
60
    {
61
        $value = implode(' ', $values);
62
63
        return sha1($value);
64
    }
65
}
66