Skip to content

Commit e91b729

Browse files
author
Babichev Maxim
committed
add static balance
1 parent 27b1bc3 commit e91b729

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

src/Traits/HasWallet.php

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,9 @@ trait HasWallet
2424
{
2525

2626
/**
27-
* @var int
27+
* @var array
2828
*/
29-
protected $cachedBalance;
29+
protected static $cachedBalances = [];
3030

3131
/**
3232
* @param int $amount
@@ -167,7 +167,7 @@ protected function assemble(Wallet $wallet, Transaction $withdraw, Transaction $
167167
protected function change(int $amount, ?array $meta, bool $confirmed): Transaction
168168
{
169169
$this->getBalanceAttribute();
170-
$this->cachedBalance += $amount;
170+
static::$cachedBalances[$this->getKey()] += $amount;
171171
return $this->transactions()->create([
172172
'type' => $amount > 0 ? 'deposit' : 'withdraw',
173173
'payable_type' => $this->getMorphClass(),
@@ -206,11 +206,27 @@ public function balance(): MorphMany
206206
}
207207

208208
/**
209+
* Example:
210+
* $user1 = User::first()->load('balance');
211+
* $user2 = User::first()->load('balance');
212+
*
213+
* Without static:
214+
* var_dump($user1->balance, $user2->balance); // 100 100
215+
* $user1->deposit(100);
216+
* $user2->deposit(100);
217+
* var_dump($user1->balance, $user2->balance); // 200 200
218+
*
219+
* With static:
220+
* var_dump($user1->balance, $user2->balance); // 100 100
221+
* $user1->deposit(100);
222+
* $user2->deposit(100);
223+
* var_dump($user1->balance, $user2->balance); // 200 300
224+
*
209225
* @return int
210226
*/
211227
public function getBalanceAttribute(): int
212228
{
213-
if (null === $this->cachedBalance) {
229+
if (!\array_key_exists($this->getKey(), static::$cachedBalances)) {
214230
if (!\array_key_exists('balance', $this->relations)) {
215231
$this->load('balance');
216232
}
@@ -220,10 +236,10 @@ public function getBalanceAttribute(): int
220236
*/
221237
$collection = $this->getRelation('balance');
222238
$relation = $collection->first();
223-
$this->cachedBalance = (int)($relation->total ?? 0);
239+
static::$cachedBalances[$this->getKey()] = (int)($relation->total ?? 0);
224240
}
225241

226-
return $this->cachedBalance;
242+
return static::$cachedBalances[$this->getKey()];
227243
}
228244

229245
}

0 commit comments

Comments
 (0)