Completed
Pull Request — master (#83)
by Бабичев
11:30
created

LockService   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Test Coverage

Coverage 70.59%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 17
c 2
b 1
f 0
dl 0
loc 54
ccs 12
cts 17
cp 0.7059
rs 10
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A lock() 0 4 1
A bindTo() 0 6 2
A lockProvider() 0 19 5
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
        try {
49
            /**
50
             * @var LockProvider $store
51
             */
52 46
            $store = Cache::getStore();
53 46
            $enabled = config('wallet.lock.enabled', false);
54
55 46
            if ($enabled && $store instanceof LockProvider) {
56 46
                $uniqId = \get_class($self);
57 46
                if ($self instanceof Model) {
58
                    $uniqId .= $self->getKey();
59
                }
60
61 46
                return $store->lock("$name.$uniqId", $seconds);
62
            }
63
        } catch (\Throwable $throwable) {
64
            return new EmptyLock();
65
        }
66
    }
67
68
}
69