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

LockService::lockProvider()   A

Complexity

Conditions 6
Paths 12

Size

Total Lines 27
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6.0163

Importance

Changes 6
Bugs 2 Features 0
Metric Value
cc 6
eloc 13
c 6
b 2
f 0
nc 12
nop 3
dl 0
loc 27
ccs 12
cts 13
cp 0.9231
crap 6.0163
rs 9.2222
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
        } catch (\Throwable $throwable) {
68
            // todo: write error's
69
        }
70
71 69
        $enabled = false;
72 69
        if (isset($store)) {
73 69
            $enabled = config('wallet.lock.enabled', false);
74
        }
75
76 69
        if ($enabled && $store instanceof LockProvider) {
77 15
            $class = \get_class($self);
78 15
            $uniqId = $class . $this->uniqId;
79 15
            if ($self instanceof Model) {
80 6
                $uniqId = $class . $self->getKey();
81
            }
82
83 15
            return $store->lock("$name.$uniqId", $seconds);
84
        }
85
86 54
        return new EmptyLock();
87
    }
88
89
}
90