Passed
Push — master ( f59eaf...1c59b9 )
by Бабичев
409:56 queued 318:29
created

LockService::lockProvider()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 5

Importance

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