Passed
Branch master (10afab)
by Бабичев
589:34 queued 502:55
created

LockService::cache()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 2
eloc 4
c 1
b 1
f 0
nc 2
nop 0
dl 0
loc 6
ccs 0
cts 0
cp 0
crap 6
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\Contracts\Cache\Store;
9
use Illuminate\Database\Eloquent\Model;
10
use Illuminate\Support\Facades\Cache;
11
use Illuminate\Support\Str;
12
13
class LockService
14
{
15
16
    /**
17
     * @var string
18
     */
19
    protected $uniqId;
20
21
    /**
22
     * LockService constructor.
23
     */
24 72
    public function __construct()
25
    {
26 72
        $this->uniqId = Str::random();
27 72
    }
28
29
    /**
30
     * @param object $self
31
     * @param string $name
32
     * @param \Closure $closure
33
     * @return mixed
34
     */
35 71
    public function lock($self, string $name, \Closure $closure)
36
    {
37 71
        return $this->lockProvider($self, $name, (int)config('wallet.lock.seconds'))
38 71
            ->get($this->bindTo($self, $closure));
39
    }
40
41
    /**
42
     * @param object $self
43
     * @param \Closure $closure
44
     * @return \Closure
45
     */
46 71
    protected function bindTo($self, \Closure $closure): \Closure
47
    {
48
        try {
49 71
            return $closure->bindTo($self);
50 68
        } catch (\Throwable $throwable) {
51 68
            return $closure;
52
        }
53
    }
54
55
    /**
56
     * @return Store|null
57
     * @codeCoverageIgnore
58
     */
59
    protected function cache(): ?Store
60
    {
61
        try {
62
            return Cache::getStore();
63
        } catch (\Throwable $throwable) {
64
            return null;
65
        }
66
    }
67
68
    /**
69
     * @param object $self
70
     * @param string $name
71
     * @param int $seconds
72
     * @return Lock
73
     */
74 71
    protected function lockProvider($self, string $name, int $seconds): Lock
75
    {
76 71
        $store = $this->cache();
77 71
        $enabled = $store && config('wallet.lock.enabled', false);
78
79
        // fixme: CodeClimate
80
        // @codeCoverageIgnoreStart
81
        if ($enabled && $store instanceof LockProvider) {
82
            $class = \get_class($self);
83
            $uniqId = $class . $this->uniqId;
84
            if ($self instanceof Model) {
85
                $uniqId = $class . $self->getKey();
86
            }
87
88
            return $store->lock("$name.$uniqId", $seconds);
89
        }
90
        // @codeCoverageIgnoreEnd
91
92 56
        return app(EmptyLock::class);
93
    }
94
95
}
96