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
|
|
|
/** |
63
|
|
|
* @var LockProvider $store |
64
|
|
|
*/ |
65
|
69 |
|
$store = Cache::getStore(); |
66
|
69 |
|
$enabled = config('wallet.lock.enabled', false); |
67
|
|
|
|
68
|
69 |
|
if ($enabled && $store instanceof LockProvider) { |
69
|
15 |
|
$class = \get_class($self); |
70
|
15 |
|
$uniqId = $class . $this->uniqId; |
71
|
15 |
|
if ($self instanceof Model) { |
72
|
6 |
|
$uniqId = $class . $self->getKey(); |
73
|
|
|
} |
74
|
|
|
|
75
|
15 |
|
return $store->lock("$name.$uniqId", $seconds); |
76
|
|
|
} |
77
|
|
|
|
78
|
54 |
|
return new EmptyLock(); |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
} |
82
|
|
|
|