Completed
Pull Request — master (#107)
by Бабичев
177:43 queued 73:46
created

LockService   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 80
Duplicated Lines 0 %

Test Coverage

Coverage 89.47%

Importance

Changes 8
Bugs 4 Features 0
Metric Value
eloc 23
c 8
b 4
f 0
dl 0
loc 80
ccs 17
cts 19
cp 0.8947
rs 10
wmc 11

5 Methods

Rating   Name   Duplication   Size   Complexity  
A lock() 0 4 1
A __construct() 0 3 1
A bindTo() 0 6 2
A cache() 0 6 2
A lockProvider() 0 20 5
1
<?php
2
3
namespace Bavix\Wallet\Services;
4
5
use Illuminate\Contracts\Cache\Lock;
6
use Illuminate\Contracts\Cache\LockProvider;
7
use Illuminate\Contracts\Cache\Store;
8
use Illuminate\Database\Eloquent\Model;
9
use Illuminate\Support\Facades\Cache;
10
use Illuminate\Support\Str;
11
12
class LockService
13
{
14
15
    /**
16
     * @var string
17
     */
18
    protected $uniqId;
19
20
    /**
21
     * LockService constructor.
22
     */
23 69
    public function __construct()
24
    {
25 69
        $this->uniqId = Str::random();
26 69
    }
27
28
    /**
29
     * @param object $self
30
     * @param string $name
31
     * @param \Closure $closure
32
     * @return mixed
33
     */
34 69
    public function lock($self, string $name, \Closure $closure)
35
    {
36 69
        return $this->lockProvider($self, $name, (int)config('wallet.lock.seconds'))
37 69
            ->get($this->bindTo($self, $closure));
38
    }
39
40
    /**
41
     * @param object $self
42
     * @param \Closure $closure
43
     * @return \Closure
44
     */
45 69
    protected function bindTo($self, \Closure $closure): \Closure
46
    {
47
        try {
48 69
            return $closure->bindTo($self);
49 66
        } catch (\Throwable $throwable) {
50 66
            return $closure;
51
        }
52
    }
53
54
    /**
55
     * @return Store|null
56
     */
57 69
    protected function cache(): ?Store
58
    {
59
        try {
60 69
            return Cache::getStore();
61
        } catch (\Throwable $throwable) {
62
            return null;
63
        }
64
    }
65
66
    /**
67
     * @param object $self
68
     * @param string $name
69
     * @param int $seconds
70
     * @return Lock
71
     */
72 69
    protected function lockProvider($self, string $name, int $seconds): Lock
73
    {
74 69
        $store = $this->cache();
75 69
        $enabled = $store && config('wallet.lock.enabled', false);
76
77
        // fixme: CodeClimate
78
        // @codeCoverageIgnoreStart
79
        if ($enabled && $store instanceof LockProvider) {
80
            $class = \get_class($self);
81
            $uniqId = $class . $this->uniqId;
82
            if ($self instanceof Model) {
83
                $uniqId = $class . $self->getKey();
84
            }
85
86
            return $store->lock("$name.$uniqId", $seconds);
87
        }
88
        // @codeCoverageIgnoreEnd
89
90 54
        return app(MakeService::class)
91 54
            ->makeEmptyLock();
92
    }
93
94
}
95