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

LockService::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
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\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