|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Bavix\Wallet\Services; |
|
4
|
|
|
|
|
5
|
|
|
use Bavix\Wallet\Exceptions\AmountInvalid; |
|
6
|
|
|
use Bavix\Wallet\Interfaces\Taxing; |
|
7
|
|
|
use Bavix\Wallet\Interfaces\Wallet; |
|
8
|
|
|
use Bavix\Wallet\Models\Wallet as WalletModel; |
|
9
|
|
|
use Bavix\Wallet\Traits\HasWallet; |
|
10
|
|
|
use function app; |
|
11
|
|
|
|
|
12
|
|
|
class WalletService |
|
13
|
|
|
{ |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* Consider the fee that the system will receive. |
|
17
|
|
|
* |
|
18
|
|
|
* @param Wallet $wallet |
|
19
|
|
|
* @param int $amount |
|
20
|
|
|
* @return int |
|
21
|
|
|
*/ |
|
22
|
20 |
|
public function fee(Wallet $wallet, int $amount): int |
|
23
|
|
|
{ |
|
24
|
20 |
|
if ($wallet instanceof Taxing) { |
|
25
|
1 |
|
return (int)($amount * $wallet->getFeePercent() / 100); |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
20 |
|
return 0; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* The amount of checks for errors |
|
33
|
|
|
* |
|
34
|
|
|
* @param int $amount |
|
35
|
|
|
* @throws |
|
36
|
|
|
*/ |
|
37
|
35 |
|
public function checkAmount(int $amount): void |
|
38
|
|
|
{ |
|
39
|
35 |
|
if ($amount < 0) { |
|
40
|
3 |
|
throw new AmountInvalid(trans('wallet::errors.price_positive')); |
|
|
|
|
|
|
41
|
|
|
} |
|
42
|
32 |
|
} |
|
43
|
|
|
|
|
44
|
|
|
/** |
|
45
|
|
|
* @param Wallet $object |
|
46
|
|
|
* @return WalletModel |
|
47
|
|
|
*/ |
|
48
|
42 |
|
public function getWallet(Wallet $object): WalletModel |
|
49
|
|
|
{ |
|
50
|
42 |
|
if ($object instanceof WalletModel) { |
|
51
|
35 |
|
return $object; |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
/** |
|
55
|
|
|
* @var HasWallet $object |
|
56
|
|
|
*/ |
|
57
|
41 |
|
return $object->wallet; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
/** |
|
61
|
|
|
* @param Wallet $object |
|
62
|
|
|
* @return int |
|
63
|
|
|
*/ |
|
64
|
42 |
|
public function getBalance(Wallet $object): int |
|
65
|
|
|
{ |
|
66
|
42 |
|
$wallet = $this->getWallet($object); |
|
67
|
42 |
|
$wallet->exists or $wallet->save(); |
|
68
|
42 |
|
$proxy = app(ProxyService::class); |
|
69
|
42 |
|
if (!$proxy->has($wallet->getKey())) { |
|
|
|
|
|
|
70
|
42 |
|
$proxy->set($wallet->getKey(), (int)($this->attributes['balance'] ?? 0)); |
|
|
|
|
|
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
42 |
|
return $proxy[$wallet->getKey()]; |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
|
|
/** |
|
77
|
|
|
* @param WalletModel $wallet |
|
78
|
|
|
* @return bool |
|
79
|
|
|
*/ |
|
80
|
2 |
|
public function refresh(WalletModel $wallet): bool |
|
81
|
|
|
{ |
|
82
|
2 |
|
$balance = $wallet->getAvailableBalance(); |
|
83
|
2 |
|
$wallet->balance = $balance; |
|
84
|
|
|
|
|
85
|
2 |
|
$proxy = app(ProxyService::class); |
|
86
|
2 |
|
$proxy->set($wallet->getKey(), $balance); |
|
|
|
|
|
|
87
|
|
|
|
|
88
|
2 |
|
return $wallet->save(); |
|
89
|
|
|
} |
|
90
|
|
|
|
|
91
|
|
|
} |
|
92
|
|
|
|