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
|
52 |
|
public function lock($self, string $name, \Closure $closure) |
21
|
|
|
{ |
22
|
52 |
|
return $this->lockProvider($self, $name, (int)config('wallet.lock.seconds')) |
23
|
52 |
|
->get($this->bindTo($self, $closure)); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param object $self |
28
|
|
|
* @param \Closure $closure |
29
|
|
|
* @return \Closure |
30
|
|
|
*/ |
31
|
52 |
|
protected function bindTo($self, \Closure $closure): \Closure |
32
|
|
|
{ |
33
|
|
|
try { |
34
|
52 |
|
return $closure->bindTo($self); |
35
|
49 |
|
} catch (\Throwable $throwable) { |
36
|
49 |
|
return $closure; |
37
|
|
|
} |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param object $self |
42
|
|
|
* @param string $name |
43
|
|
|
* @param int $seconds |
44
|
|
|
* @return Lock |
45
|
|
|
*/ |
46
|
52 |
|
protected function lockProvider($self, string $name, int $seconds): Lock |
47
|
|
|
{ |
48
|
|
|
try { |
49
|
|
|
/** |
50
|
|
|
* @var LockProvider $store |
51
|
|
|
*/ |
52
|
52 |
|
$store = Cache::getStore(); |
53
|
52 |
|
$enabled = config('wallet.lock.enabled', false); |
54
|
|
|
|
55
|
52 |
|
if ($enabled && $store instanceof LockProvider) { |
56
|
52 |
|
$uniqId = \get_class($self); |
57
|
52 |
|
if ($self instanceof Model) { |
58
|
7 |
|
$uniqId .= $self->getKey(); |
59
|
|
|
} |
60
|
|
|
|
61
|
52 |
|
return $store->lock("$name.$uniqId", $seconds); |
62
|
|
|
} |
63
|
|
|
} catch (\Throwable $throwable) { |
64
|
|
|
// write error's |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
return new EmptyLock(); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
} |
71
|
|
|
|