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

LockService::lockProvider()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 18
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4.1755

Importance

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