1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Bavix\Wallet\Services; |
4
|
|
|
|
5
|
|
|
use Bavix\Wallet\Interfaces\Wallet; |
6
|
|
|
use Bavix\Wallet\Models\Transaction; |
7
|
|
|
use Bavix\Wallet\Models\Transfer; |
8
|
|
|
use Bavix\Wallet\Models\Wallet as WalletModel; |
9
|
|
|
use Bavix\Wallet\Objects\Bring; |
10
|
|
|
use Bavix\Wallet\Objects\Operation; |
11
|
|
|
use Illuminate\Database\Eloquent\Model; |
12
|
|
|
use Ramsey\Uuid\Uuid; |
13
|
|
|
|
14
|
|
|
class CommonService |
15
|
|
|
{ |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @param Wallet $self |
19
|
|
|
* @param Operation[] $transactions |
20
|
|
|
* @return Transaction[] |
21
|
|
|
*/ |
22
|
28 |
|
public function enforce(Wallet $self, array $transactions): array |
23
|
|
|
{ |
24
|
28 |
|
$objects = []; |
25
|
28 |
|
$amount = 0; |
26
|
|
|
|
27
|
28 |
|
foreach ($transactions as $transaction) { |
28
|
28 |
|
if ($transaction->isConfirmed()) { |
29
|
28 |
|
$amount += $transaction->getAmount(); |
30
|
|
|
} |
31
|
|
|
|
32
|
28 |
|
$objects[] = $transaction->create($self); |
33
|
|
|
} |
34
|
|
|
|
35
|
28 |
|
$this->addBalance($self, $amount); |
36
|
28 |
|
return $objects; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @param Bring[] $brings |
41
|
|
|
* @return array |
42
|
|
|
* @throws |
43
|
|
|
*/ |
44
|
17 |
|
public function assemble(array $brings): array |
45
|
|
|
{ |
46
|
17 |
|
$objects = []; |
47
|
17 |
|
foreach ($brings as $bring) { |
48
|
17 |
|
$objects[] = $bring->create(); |
49
|
|
|
} |
50
|
|
|
|
51
|
17 |
|
return $objects; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @param Wallet $wallet |
57
|
|
|
* @param int $amount |
58
|
|
|
* @return bool |
59
|
|
|
* @throws |
60
|
|
|
*/ |
61
|
28 |
|
public function addBalance(Wallet $wallet, int $amount): bool |
62
|
|
|
{ |
63
|
|
|
/** |
64
|
|
|
* @var ProxyService $proxy |
65
|
|
|
* @var \Bavix\Wallet\Models\Wallet $wallet |
66
|
|
|
*/ |
67
|
28 |
|
$proxy = \app(ProxyService::class); |
68
|
28 |
|
$balance = $wallet->balance; |
69
|
28 |
|
if ($proxy->has($wallet->getKey())) { |
|
|
|
|
70
|
28 |
|
$balance = $proxy->get($wallet->getKey()); |
|
|
|
|
71
|
|
|
} |
72
|
|
|
|
73
|
28 |
|
$balance += $amount; |
74
|
28 |
|
if ($wallet->update(\compact('balance'))) { |
75
|
28 |
|
$proxy->set($wallet->getKey(), $balance); |
|
|
|
|
76
|
28 |
|
return true; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
return false; |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
} |
83
|
|
|
|