|
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
|
|
|
/** |
|
49
|
|
|
* @var LockProvider $store |
|
50
|
|
|
*/ |
|
51
|
46 |
|
$store = Cache::getStore(); |
|
52
|
46 |
|
$enabled = config('wallet.lock.enabled', false); |
|
53
|
|
|
|
|
54
|
46 |
|
if ($enabled && $store instanceof LockProvider) { |
|
55
|
46 |
|
$uniqId = \get_class($self); |
|
56
|
46 |
|
if ($self instanceof Model) { |
|
57
|
|
|
$uniqId .= $self->getKey(); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
46 |
|
return $store->lock($name, $seconds, $uniqId); |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
return new EmptyLock(); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
} |
|
67
|
|
|
|