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