Test Failed
Pull Request — master (#83)
by Бабичев
04:54
created

LockService::lock()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 3
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
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\Support\Facades\Cache;
9
10
class LockService
11
{
12
13
    /**
14
     * @param object $self
15
     * @param string $name
16
     * @param \Closure $closure
17
     * @return mixed
18
     */
19 46
    public function lock($self, string $name, \Closure $closure)
20
    {
21 46
        return $this->lockProvider($name, (int)config('wallet.lock.seconds'))
22 46
            ->get($this->bindTo($self, $closure));
23
    }
24
25
    /**
26
     * @param object $self
27
     * @param \Closure $closure
28
     * @return \Closure
29
     */
30 46
    protected function bindTo($self, \Closure $closure): \Closure
31
    {
32
        try {
33 46
            return $closure->bindTo($self);
34
        } catch (\Throwable $throwable) {
35
            return $closure;
36
        }
37
    }
38
39
    /**
40
     * @param string $name
41
     * @param int $seconds
42
     * @return Lock
43
     */
44 46
    protected function lockProvider(string $name, int $seconds): Lock
45
    {
46
        /**
47
         * @var LockProvider $store
48
         */
49 46
        $store = Cache::getStore();
50 46
        $enabled = config('wallet.lock.enabled', false);
51
52 46
        if ($enabled && $store instanceof LockProvider) {
53 46
            return $store->lock($name, $seconds);
54
        }
55
56
        return new EmptyLock();
57
    }
58
59
}
60