1 | <?php |
||
2 | |||
3 | namespace Bavix\Wallet\Simple; |
||
4 | |||
5 | use Bavix\Wallet\Interfaces\Mathable; |
||
6 | use Bavix\Wallet\Interfaces\Storable; |
||
7 | use Bavix\Wallet\Services\WalletService; |
||
8 | |||
9 | class Store implements Storable |
||
10 | { |
||
11 | /** |
||
12 | * @var array |
||
13 | */ |
||
14 | protected $balanceSheets = []; |
||
15 | |||
16 | /** |
||
17 | * {@inheritdoc} |
||
18 | */ |
||
19 | 125 | public function getBalance($object) |
|
20 | { |
||
21 | 125 | $wallet = app(WalletService::class)->getWallet($object); |
|
22 | 125 | if (! \array_key_exists($wallet->getKey(), $this->balanceSheets)) { |
|
23 | 125 | $balance = method_exists($wallet, 'getRawOriginal') ? |
|
24 | 125 | $wallet->getRawOriginal('balance', 0) : $wallet->getOriginal('balance', 0); |
|
25 | |||
26 | 125 | $this->balanceSheets[$wallet->getKey()] = $this->toInt($balance); |
|
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
27 | } |
||
28 | |||
29 | 125 | return $this->balanceSheets[$wallet->getKey()]; |
|
30 | } |
||
31 | |||
32 | /** |
||
33 | * {@inheritdoc} |
||
34 | */ |
||
35 | 114 | public function incBalance($object, $amount) |
|
36 | { |
||
37 | 114 | $math = app(Mathable::class); |
|
38 | 114 | $balance = $math->add($this->getBalance($object), $amount); |
|
39 | 114 | $balance = $this->toInt($balance); |
|
40 | 114 | $this->setBalance($object, $balance); |
|
41 | |||
42 | 114 | return $balance; |
|
43 | } |
||
44 | |||
45 | /** |
||
46 | * {@inheritdoc} |
||
47 | */ |
||
48 | 114 | public function setBalance($object, $amount): bool |
|
49 | { |
||
50 | 114 | $wallet = app(WalletService::class)->getWallet($object); |
|
51 | 114 | $this->balanceSheets[$wallet->getKey()] = $this->toInt($amount); |
|
52 | |||
53 | 114 | return true; |
|
54 | } |
||
55 | |||
56 | /** |
||
57 | * {@inheritdoc} |
||
58 | */ |
||
59 | 180 | public function fresh(): bool |
|
60 | { |
||
61 | 180 | $this->balanceSheets = []; |
|
62 | |||
63 | 180 | return true; |
|
64 | } |
||
65 | |||
66 | /** |
||
67 | * @param string $balance |
||
68 | * @return string |
||
69 | */ |
||
70 | 125 | protected function toInt($balance): string |
|
71 | { |
||
72 | 125 | return app(Mathable::class)->round($balance ?: 0); |
|
73 | } |
||
74 | } |
||
75 |