1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Bavix\Wallet\Traits; |
4
|
|
|
|
5
|
|
|
use Bavix\Wallet\Models\Wallet as WalletModel; |
6
|
|
|
use Illuminate\Database\Eloquent\Relations\MorphMany; |
7
|
|
|
use Illuminate\Support\Collection; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Trait HasWallets |
11
|
|
|
* To use a trait, you must add HasWallet trait. |
12
|
|
|
* |
13
|
|
|
* @package Bavix\Wallet\Traits |
14
|
|
|
* |
15
|
|
|
* @property-read Collection|WalletModel[] $wallets |
16
|
|
|
*/ |
17
|
|
|
trait HasWallets |
18
|
|
|
{ |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* The variable is used for the cache, so as not to request wallets many times. |
22
|
|
|
* WalletProxy keeps the money wallets in the memory to avoid errors when you |
23
|
|
|
* purchase/transfer, etc. |
24
|
|
|
* |
25
|
|
|
* @var array |
26
|
|
|
*/ |
27
|
|
|
private $_wallets = []; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* method of obtaining all wallets |
31
|
|
|
* |
32
|
|
|
* @return MorphMany |
33
|
|
|
*/ |
34
|
8 |
|
public function wallets(): MorphMany |
35
|
|
|
{ |
36
|
8 |
|
return $this->morphMany(config('wallet.wallet.model'), 'holder'); |
|
|
|
|
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Get wallet by slug |
41
|
|
|
* |
42
|
|
|
* $user->wallet->balance // 200 |
43
|
|
|
* or short recording $user->balance; // 200 |
44
|
|
|
* |
45
|
|
|
* $defaultSlug = config('wallet.wallet.default.slug'); |
46
|
|
|
* $user->getWallet($defaultSlug)->balance; // 200 |
47
|
|
|
* |
48
|
|
|
* $user->getWallet('usd')->balance; // 50 |
49
|
|
|
* $user->getWallet('rub')->balance; // 100 |
50
|
|
|
* |
51
|
|
|
* @param string $slug |
52
|
|
|
* @return WalletModel|null |
53
|
|
|
*/ |
54
|
|
|
public function getWallet(string $slug): ?WalletModel |
55
|
|
|
{ |
56
|
|
|
if (!\array_key_exists($slug, $this->_wallets)) { |
57
|
|
|
$this->_wallets[$slug] = $this->wallets() |
58
|
|
|
->where('slug', $slug) |
59
|
|
|
->first(); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
return $this->_wallets[$slug]; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @param array $data |
67
|
|
|
* @return WalletModel |
68
|
|
|
*/ |
69
|
8 |
|
public function createWallet(array $data): WalletModel |
70
|
|
|
{ |
71
|
|
|
/** |
72
|
|
|
* Create a default wallet |
73
|
|
|
*/ |
74
|
8 |
|
$this->getBalanceAttribute(); |
|
|
|
|
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* @var WalletModel $wallet |
78
|
|
|
*/ |
79
|
8 |
|
$wallet = $this->wallets()->create($data); |
80
|
8 |
|
if ($this->wallets()->save($wallet)) { |
81
|
8 |
|
$this->_wallets[$wallet->slug] = $wallet; |
82
|
|
|
} |
83
|
|
|
|
84
|
8 |
|
return $wallet; |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
} |
88
|
|
|
|