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
|
131 |
|
public function getBalance($object) |
20
|
|
|
{ |
21
|
131 |
|
$wallet = app(WalletService::class)->getWallet($object); |
22
|
131 |
|
if (! \array_key_exists($wallet->getKey(), $this->balanceSheets)) { |
23
|
131 |
|
$balance = method_exists($wallet, 'getRawOriginal') ? |
24
|
131 |
|
$wallet->getRawOriginal('balance', 0) : $wallet->getOriginal('balance', 0); |
25
|
|
|
|
26
|
131 |
|
$this->balanceSheets[$wallet->getKey()] = $this->toInt($balance); |
|
|
|
|
27
|
|
|
} |
28
|
|
|
|
29
|
131 |
|
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
|
170 |
|
public function fresh(): bool |
60
|
|
|
{ |
61
|
170 |
|
$this->balanceSheets = []; |
62
|
170 |
|
return true; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @param string $balance |
67
|
|
|
* @return string |
68
|
|
|
*/ |
69
|
131 |
|
protected function toInt($balance): string |
70
|
|
|
{ |
71
|
131 |
|
return app(Mathable::class)->round($balance ?: 0); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|