Passed
Pull Request — master (#83)
by Бабичев
06:33
created

LockService::lockProvider()   A

Complexity

Conditions 5
Paths 9

Size

Total Lines 23
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5.0187

Importance

Changes 5
Bugs 2 Features 0
Metric Value
cc 5
eloc 11
c 5
b 2
f 0
nc 9
nop 3
dl 0
loc 23
ccs 10
cts 11
cp 0.9091
crap 5.0187
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\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
     * @param object $self
56
     * @param string $name
57
     * @param int $seconds
58
     * @return Lock
59
     */
60 69
    protected function lockProvider($self, string $name, int $seconds): Lock
61
    {
62
        try {
63
            /**
64
             * @var LockProvider $store
65
             */
66 69
            $store = Cache::getStore();
67 69
            $enabled = config('wallet.lock.enabled', false);
68
69 69
            if ($enabled && $store instanceof LockProvider) {
70 15
                $class = \get_class($self);
71 15
                $uniqId = $class . $this->uniqId;
72 15
                if ($self instanceof Model) {
73 6
                    $uniqId = $class . $self->getKey();
74
                }
75
76 69
                return $store->lock("$name.$uniqId", $seconds);
77
            }
78
        } catch (\Throwable $throwable) {
79
            // write error's
80
        }
81
82 54
        return new EmptyLock();
83
    }
84
85
}
86