1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Bavix\Wallet\Traits; |
4
|
|
|
|
5
|
|
|
use Bavix\Wallet\Interfaces\Product; |
6
|
|
|
use Bavix\Wallet\Interfaces\Wallet; |
7
|
|
|
use Bavix\Wallet\Models\Transfer; |
8
|
|
|
use Bavix\Wallet\Tax; |
9
|
|
|
use Illuminate\Support\Facades\DB; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Trait HasGift |
13
|
|
|
* @package Bavix\Wallet\Traits |
14
|
|
|
* |
15
|
|
|
* This trait should be used with the trait HasWallet. |
16
|
|
|
*/ |
17
|
|
|
trait HasGift |
18
|
|
|
{ |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* From this moment on, each user (wallet) can give |
22
|
|
|
* the goods to another user (wallet). |
23
|
|
|
* This functionality can be organized for gifts. |
24
|
|
|
* |
25
|
|
|
* @param Wallet $to |
26
|
|
|
* @param Product $product |
27
|
|
|
* @param bool $force |
28
|
|
|
* @return Transfer |
29
|
|
|
*/ |
30
|
2 |
|
public function gift(Wallet $to, Product $product, bool $force = false): Transfer |
31
|
|
|
{ |
32
|
|
|
/** |
33
|
|
|
* Who's giving? Let's call him Santa Claus |
34
|
|
|
*/ |
35
|
2 |
|
$santa = $this; |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @return Transfer |
39
|
|
|
*/ |
40
|
|
|
$callback = function () use ($santa, $product, $force) { |
41
|
2 |
|
$amount = $product->getAmountProduct(); |
42
|
2 |
|
$meta = $product->getMetaProduct(); |
43
|
2 |
|
$fee = Tax::fee($product, $amount); |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Santa pays taxes |
47
|
|
|
*/ |
48
|
2 |
|
if ($force) { |
49
|
|
|
$withdraw = $santa->withdraw($amount + $fee, $meta); |
|
|
|
|
50
|
|
|
} else { |
51
|
2 |
|
$withdraw = $santa->forceWithdraw($amount + $fee, $meta); |
|
|
|
|
52
|
|
|
} |
53
|
|
|
|
54
|
2 |
|
$deposit = $product->deposit($amount, $meta); |
55
|
2 |
|
return $this->assemble($product, $withdraw, $deposit); |
|
|
|
|
56
|
2 |
|
}; |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* Unfortunately, |
60
|
|
|
* I think it is wrong to make the "assemble" method public. |
61
|
|
|
* That's why I address him like this! |
62
|
|
|
*/ |
63
|
2 |
|
return DB::transaction( |
64
|
2 |
|
$callback->bindTo($to, \get_class($to)) |
65
|
|
|
); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* Give the goods safely. |
70
|
|
|
* |
71
|
|
|
* @param Wallet $to |
72
|
|
|
* @param Product $product |
73
|
|
|
* @param bool $force |
74
|
|
|
* @return Transfer|null |
75
|
|
|
*/ |
76
|
|
|
public function safeGift(Wallet $to, Product $product, bool $force = false): ?Transfer |
77
|
|
|
{ |
78
|
|
|
try { |
79
|
|
|
return $this->gift($to, $product, $force); |
80
|
|
|
} catch (\Throwable $throwable) { |
81
|
|
|
return null; |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
/** |
86
|
|
|
* to give force) |
87
|
|
|
* |
88
|
|
|
* @param Wallet $to |
89
|
|
|
* @param Product $product |
90
|
|
|
* @return Transfer |
91
|
|
|
*/ |
92
|
|
|
public function forceGift(Wallet $to, Product $product): Transfer |
93
|
|
|
{ |
94
|
|
|
return $this->gift($to, $product, true); |
95
|
|
|
} |
96
|
|
|
|
97
|
|
|
} |
98
|
|
|
|