Completed
Pull Request — master (#40)
by Бабичев
05:28
created

HasWallet::holderTransfers()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Bavix\Wallet\Traits;
4
5
use Bavix\Wallet\Exceptions\BalanceIsEmpty;
6
use Bavix\Wallet\Exceptions\InsufficientFunds;
7
use Bavix\Wallet\Interfaces\Wallet;
8
use Bavix\Wallet\Models\Transaction;
9
use Bavix\Wallet\Models\Transfer;
10
use Bavix\Wallet\Models\Wallet as WalletModel;
11
use Bavix\Wallet\Objects\Bring;
12
use Bavix\Wallet\Objects\Operation;
13
use Bavix\Wallet\Services\CommonService;
14
use Bavix\Wallet\Services\ProxyService;
15
use Bavix\Wallet\Services\WalletService;
16
use Illuminate\Database\Eloquent\Relations\MorphMany;
17
use Illuminate\Database\Eloquent\Relations\MorphOne;
18
use Illuminate\Support\Collection;
19
use Illuminate\Support\Facades\DB;
20
use Throwable;
21
use function app;
22
use function config;
23
use function current;
24
25
/**
26
 * Trait HasWallet
27
 *
28
 * @package Bavix\Wallet\Traits
29
 *
30
 * @property-read WalletModel $wallet
31
 * @property-read Collection|WalletModel[] $wallets
32
 * @property-read int $balance
33
 */
34
trait HasWallet
35
{
36
37
    /**
38
     * The input means in the system
39
     *
40
     * @param int $amount
41
     * @param array|null $meta
42
     * @param bool $confirmed
43
     *
44
     * @return Transaction
45
     */
46 33
    public function deposit(int $amount, ?array $meta = null, bool $confirmed = true): Transaction
47
    {
48 33
        $walletService = app(WalletService::class);
49 33
        $walletService->checkAmount($amount);
50
51
        /**
52
         * @var WalletModel $wallet
53
         */
54 30
        $wallet = $walletService->getWallet($this);
0 ignored issues
show
Bug introduced by
$this of type Bavix\Wallet\Traits\HasWallet is incompatible with the type Bavix\Wallet\Interfaces\Wallet expected by parameter $object of Bavix\Wallet\Services\WalletService::getWallet(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

54
        $wallet = $walletService->getWallet(/** @scrutinizer ignore-type */ $this);
Loading history...
55
56 30
        $transactions = app(CommonService::class)->enforce($wallet, [
57 30
            (new Operation())
58 30
                ->setType(Transaction::TYPE_DEPOSIT)
59 30
                ->setConfirmed($confirmed)
60 30
                ->setAmount($amount)
61 30
                ->setMeta($meta)
62
        ]);
63
64 30
        return current($transactions);
65
    }
66
67
    /**
68
     * Magic laravel framework method, makes it
69
     *  possible to call property balance
70
     *
71
     * Example:
72
     *  $user1 = User::first()->load('wallet');
73
     *  $user2 = User::first()->load('wallet');
74
     *
75
     * Without static:
76
     *  var_dump($user1->balance, $user2->balance); // 100 100
77
     *  $user1->deposit(100);
78
     *  $user2->deposit(100);
79
     *  var_dump($user1->balance, $user2->balance); // 200 200
80
     *
81
     * With static:
82
     *  var_dump($user1->balance, $user2->balance); // 100 100
83
     *  $user1->deposit(100);
84
     *  var_dump($user1->balance); // 200
85
     *  $user2->deposit(100);
86
     *  var_dump($user2->balance); // 300
87
     *
88
     * @return int
89
     * @throws
90
     */
91 40
    public function getBalanceAttribute(): int
92
    {
93 40
        if ($this instanceof WalletModel) {
94 40
            $this->exists or $this->save();
95 40
            $proxy = app(ProxyService::class);
96 40
            if (!$proxy->has($this->getKey())) {
0 ignored issues
show
Bug introduced by
It seems like $this->getKey() can also be of type boolean and null; however, parameter $key of Bavix\Wallet\Services\ProxyService::has() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

96
            if (!$proxy->has(/** @scrutinizer ignore-type */ $this->getKey())) {
Loading history...
97 40
                $proxy->set($this->getKey(), (int)($this->attributes['balance'] ?? 0));
0 ignored issues
show
Bug Best Practice introduced by
The property $attributes is declared protected in Illuminate\Database\Eloquent\Model. Since you implement __get, consider adding a @property or @property-read.
Loading history...
Bug introduced by
It seems like $this->getKey() can also be of type boolean and null; however, parameter $key of Bavix\Wallet\Services\ProxyService::set() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

97
                $proxy->set(/** @scrutinizer ignore-type */ $this->getKey(), (int)($this->attributes['balance'] ?? 0));
Loading history...
98
            }
99
100 40
            return $proxy[$this->getKey()];
101
        }
102
103 39
        return $this->wallet->balance;
104
    }
105
106
    /**
107
     * all user actions on wallets will be in this method
108
     *
109
     * @return MorphMany
110
     */
111 30
    public function transactions(): MorphMany
112
    {
113 30
        return ($this instanceof WalletModel ? $this->holder : $this)
114 30
            ->morphMany(config('wallet.transaction.model'), 'payable');
0 ignored issues
show
Bug introduced by
It seems like morphMany() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

114
            ->/** @scrutinizer ignore-call */ morphMany(config('wallet.transaction.model'), 'payable');
Loading history...
115
    }
116
117
    /**
118
     * This method ignores errors that occur when transferring funds
119
     *
120
     * @param Wallet $wallet
121
     * @param int $amount
122
     * @param array|null $meta
123
     * @param string $status
124
     * @return null|Transfer
125
     */
126 3
    public function safeTransfer(Wallet $wallet, int $amount, ?array $meta = null, string $status = Transfer::STATUS_TRANSFER): ?Transfer
127
    {
128
        try {
129 3
            return $this->transfer($wallet, $amount, $meta, $status);
130 3
        } catch (Throwable $throwable) {
131 3
            return null;
132
        }
133
    }
134
135
    /**
136
     * A method that transfers funds from host to host
137
     *
138
     * @param Wallet $wallet
139
     * @param int $amount
140
     * @param array|null $meta
141
     * @param string $status
142
     * @return Transfer
143
     * @throws
144
     */
145 16
    public function transfer(Wallet $wallet, int $amount, ?array $meta = null, string $status = Transfer::STATUS_TRANSFER): Transfer
146
    {
147
        return DB::transaction(function () use ($amount, $wallet, $meta, $status) {
148 16
            $fee = app(WalletService::class)
149 16
                ->fee($wallet, $amount);
150
151 16
            $withdraw = $this->withdraw($amount + $fee, $meta);
152 16
            $deposit = $wallet->deposit($amount, $meta);
153 16
            return $this->assemble($wallet, $withdraw, $deposit, $status);
154 16
        });
155
    }
156
157
    /**
158
     * Withdrawals from the system
159
     *
160
     * @param int $amount
161
     * @param array|null $meta
162
     * @param bool $confirmed
163
     *
164
     * @return Transaction
165
     */
166 34
    public function withdraw(int $amount, ?array $meta = null, bool $confirmed = true): Transaction
167
    {
168 34
        if ($amount && !$this->balance) {
169 14
            throw new BalanceIsEmpty(trans('wallet::errors.wallet_empty'));
0 ignored issues
show
Bug introduced by
It seems like trans('wallet::errors.wallet_empty') can also be of type array; however, parameter $message of Bavix\Wallet\Exceptions\...eIsEmpty::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

169
            throw new BalanceIsEmpty(/** @scrutinizer ignore-type */ trans('wallet::errors.wallet_empty'));
Loading history...
170
        }
171
172 28
        if (!$this->canWithdraw($amount)) {
173 1
            throw new InsufficientFunds(trans('wallet::errors.insufficient_funds'));
0 ignored issues
show
Bug introduced by
It seems like trans('wallet::errors.insufficient_funds') can also be of type array; however, parameter $message of Bavix\Wallet\Exceptions\...entFunds::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

173
            throw new InsufficientFunds(/** @scrutinizer ignore-type */ trans('wallet::errors.insufficient_funds'));
Loading history...
174
        }
175
176 27
        return $this->forceWithdraw($amount, $meta, $confirmed);
177
    }
178
179
    /**
180
     * Checks if you can withdraw funds
181
     *
182
     * @param int $amount
183
     * @return bool
184
     */
185 28
    public function canWithdraw(int $amount): bool
186
    {
187 28
        return $this->balance >= $amount;
188
    }
189
190
    /**
191
     * Forced to withdraw funds from system
192
     *
193
     * @param int $amount
194
     * @param array|null $meta
195
     * @param bool $confirmed
196
     *
197
     * @return Transaction
198
     */
199 28
    public function forceWithdraw(int $amount, ?array $meta = null, bool $confirmed = true): Transaction
200
    {
201 28
        $walletService = app(WalletService::class);
202 28
        $walletService->checkAmount($amount);
203
204
        /**
205
         * @var WalletModel $wallet
206
         */
207 28
        $wallet = $walletService->getWallet($this);
0 ignored issues
show
Bug introduced by
$this of type Bavix\Wallet\Traits\HasWallet is incompatible with the type Bavix\Wallet\Interfaces\Wallet expected by parameter $object of Bavix\Wallet\Services\WalletService::getWallet(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

207
        $wallet = $walletService->getWallet(/** @scrutinizer ignore-type */ $this);
Loading history...
208
209 28
        $transactions = app(CommonService::class)->enforce($wallet, [
210 28
            (new Operation())
211 28
                ->setType(Transaction::TYPE_WITHDRAW)
212 28
                ->setConfirmed($confirmed)
213 28
                ->setAmount(-$amount)
214 28
                ->setMeta($meta)
215
        ]);
216
217 28
        return current($transactions);
218
    }
219
220
    /**
221
     * this method adds a new transfer to the transfer table
222
     *
223
     * @param Wallet $wallet
224
     * @param Transaction $withdraw
225
     * @param Transaction $deposit
226
     * @param string $status
227
     * @return Transfer
228
     * @throws
229
     */
230 18
    protected function assemble(Wallet $wallet, Transaction $withdraw, Transaction $deposit, string $status = Transfer::STATUS_PAID): Transfer
231
    {
232 18
        $from = ($this instanceof WalletModel ? $this : $this->wallet);
233
234 18
        $transfers = app(CommonService::class)->assemble([
235 18
            (new Bring())
236 18
                ->setStatus($status)
237 18
                ->setDeposit($deposit)
238 18
                ->setWithdraw($withdraw)
239 18
                ->setFrom($from)
240 18
                ->setTo($wallet)
241
        ]);
242
243 18
        return current($transfers);
244
    }
245
246
    /**
247
     * the forced transfer is needed when the user does not have the money and we drive it.
248
     * Sometimes you do. Depends on business logic.
249
     *
250
     * @param Wallet $wallet
251
     * @param int $amount
252
     * @param array|null $meta
253
     * @param string $status
254
     * @return Transfer
255
     */
256 6
    public function forceTransfer(Wallet $wallet, int $amount, ?array $meta = null, string $status = Transfer::STATUS_TRANSFER): Transfer
257
    {
258
        return DB::transaction(function () use ($amount, $wallet, $meta, $status) {
259 6
            $fee = app(WalletService::class)
260 6
                ->fee($wallet, $amount);
261
262 6
            $withdraw = $this->forceWithdraw($amount + $fee, $meta);
263 6
            $deposit = $wallet->deposit($amount, $meta);
264 6
            return $this->assemble($wallet, $withdraw, $deposit, $status);
265 6
        });
266
    }
267
268
    /**
269
     * the transfer table is used to confirm the payment
270
     * this method receives all transfers
271
     *
272
     * @return MorphMany
273
     */
274 11
    public function transfers(): MorphMany
275
    {
276 11
        return app(WalletService::class)
277 11
            ->getWallet($this)
0 ignored issues
show
Bug introduced by
$this of type Bavix\Wallet\Traits\HasWallet is incompatible with the type Bavix\Wallet\Interfaces\Wallet expected by parameter $object of Bavix\Wallet\Services\WalletService::getWallet(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

277
            ->getWallet(/** @scrutinizer ignore-type */ $this)
Loading history...
278 11
            ->morphMany(config('wallet.transfer.model'), 'from');
279
    }
280
281
    /**
282
     * Get default Wallet
283
     * this method is used for Eager Loading
284
     *
285
     * @return MorphOne|WalletModel
286
     */
287 40
    public function wallet(): MorphOne
288
    {
289 40
        return ($this instanceof WalletModel ? $this->holder : $this)
290 40
            ->morphOne(config('wallet.wallet.model'), 'holder')
0 ignored issues
show
Bug introduced by
It seems like morphOne() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

290
            ->/** @scrutinizer ignore-call */ morphOne(config('wallet.wallet.model'), 'holder')
Loading history...
291 40
            ->where('slug', config('wallet.wallet.default.slug'))
292 40
            ->withDefault([
293 40
                'name' => config('wallet.wallet.default.name'),
294 40
                'slug' => config('wallet.wallet.default.slug'),
295 40
                'balance' => 0,
296
            ]);
297
    }
298
299
}
300