1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Bavix\Wallet\Services; |
4
|
|
|
|
5
|
|
|
use Illuminate\Contracts\Cache\Lock; |
6
|
|
|
use Illuminate\Contracts\Cache\LockProvider; |
7
|
|
|
use Illuminate\Contracts\Cache\Store; |
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
|
|
|
* @return Store|null |
56
|
|
|
*/ |
57
|
69 |
|
protected function cache(): ?Store |
58
|
|
|
{ |
59
|
|
|
try { |
60
|
69 |
|
return Cache::getStore(); |
61
|
|
|
} catch (\Throwable $throwable) { |
62
|
|
|
return null; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* @param object $self |
68
|
|
|
* @param string $name |
69
|
|
|
* @param int $seconds |
70
|
|
|
* @return Lock |
71
|
|
|
*/ |
72
|
69 |
|
protected function lockProvider($self, string $name, int $seconds): Lock |
73
|
|
|
{ |
74
|
69 |
|
$store = $this->cache(); |
75
|
69 |
|
$enabled = $store && config('wallet.lock.enabled', false); |
76
|
|
|
|
77
|
|
|
// fixme: CodeClimate |
78
|
|
|
// @codeCoverageIgnoreStart |
79
|
|
|
if ($enabled && $store instanceof LockProvider) { |
80
|
|
|
$class = \get_class($self); |
81
|
|
|
$uniqId = $class . $this->uniqId; |
82
|
|
|
if ($self instanceof Model) { |
83
|
|
|
$uniqId = $class . $self->getKey(); |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
return $store->lock("$name.$uniqId", $seconds); |
87
|
|
|
} |
88
|
|
|
// @codeCoverageIgnoreEnd |
89
|
|
|
|
90
|
54 |
|
return app(MakeService::class) |
91
|
54 |
|
->makeEmptyLock(); |
92
|
|
|
} |
93
|
|
|
|
94
|
|
|
} |
95
|
|
|
|