Test Failed
Pull Request — master (#14)
by Бабичев
02:49
created

HasWallet::safeTransfer()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 3
dl 0
loc 6
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\AmountInvalid;
6
use Bavix\Wallet\Exceptions\BalanceIsEmpty;
7
use Bavix\Wallet\Exceptions\InsufficientFunds;
8
use Bavix\Wallet\Tax;
9
use Bavix\Wallet\Interfaces\Wallet;
10
use Bavix\Wallet\Models\Wallet as WalletModel;
11
use Bavix\Wallet\Models\Transaction;
12
use Bavix\Wallet\Models\Transfer;
13
use Bavix\Wallet\WalletProxy;
14
use Illuminate\Database\Eloquent\Model;
15
use Illuminate\Database\Eloquent\Relations\MorphMany;
16
use Illuminate\Database\Eloquent\Relations\MorphOne;
17
use Illuminate\Support\Collection;
18
use Illuminate\Support\Facades\DB;
19
use Ramsey\Uuid\Uuid;
20
21
/**
22
 * Trait HasWallet
23
 *
24
 * @package Bavix\Wallet\Traits
25
 *
26
 * @property-read WalletModel $wallet
27
 * @property-read Collection|WalletModel[] $wallets
28
 * @property-read int $balance
29
 */
30
trait HasWallet
31
{
32
33
    /**
34
     * The amount of checks for errors
35
     *
36
     * @param int $amount
37
     * @throws
38
     */
39 17
    private function checkAmount(int $amount): void
40
    {
41 17
        if ($amount < 0) {
42 2
            throw new AmountInvalid(trans('wallet::errors.price_positive'));
43
        }
44 15
    }
45
46
    /**
47
     * Forced to withdraw funds from system
48
     *
49
     * @param int $amount
50
     * @param array|null $meta
51
     * @param bool $confirmed
52
     *
53
     * @return Transaction
54
     */
55 15
    public function forceWithdraw(int $amount, ?array $meta = null, bool $confirmed = true): Transaction
56
    {
57 15
        $this->checkAmount($amount);
58 15
        return $this->change(-$amount, $meta, $confirmed);
59
    }
60
61
    /**
62
     * The input means in the system
63
     *
64
     * @param int $amount
65
     * @param array|null $meta
66
     * @param bool $confirmed
67
     *
68
     * @return Transaction
69
     */
70 17
    public function deposit(int $amount, ?array $meta = null, bool $confirmed = true): Transaction
71
    {
72 17
        $this->checkAmount($amount);
73 15
        return $this->change($amount, $meta, $confirmed);
74
    }
75
76
    /**
77
     * Withdrawals from the system
78
     *
79
     * @param int $amount
80
     * @param array|null $meta
81
     * @param bool $confirmed
82
     *
83
     * @return Transaction
84
     */
85 18
    public function withdraw(int $amount, ?array $meta = null, bool $confirmed = true): Transaction
86
    {
87 18
        if (!$this->balance) {
88 9
            throw new BalanceIsEmpty(trans('wallet::errors.wallet_empty'));
89
        }
90
91 14
        if (!$this->canWithdraw($amount)) {
92
            throw new InsufficientFunds(trans('wallet::errors.insufficient_funds'));
93
        }
94
95 14
        return $this->forceWithdraw($amount, $meta, $confirmed);
96
    }
97
98
    /**
99
     * Checks if you can withdraw funds
100
     *
101
     * @param int $amount
102
     * @return bool
103
     */
104 14
    public function canWithdraw(int $amount): bool
105
    {
106 14
        return $this->balance >= $amount;
107
    }
108
109
    /**
110
     * A method that transfers funds from host to host
111
     *
112
     * @param Wallet $wallet
113
     * @param int $amount
114
     * @param array|null $meta
115
     * @return Transfer
116
     * @throws
117
     */
118 8
    public function transfer(Wallet $wallet, int $amount, ?array $meta = null): Transfer
119
    {
120
        return DB::transaction(function() use ($amount, $wallet, $meta) {
121 8
            $fee = Tax::fee($wallet, $amount);
122 8
            $withdraw = $this->withdraw($amount + $fee, $meta);
123 8
            $deposit = $wallet->deposit($amount, $meta);
124 8
            return $this->assemble($wallet, $withdraw, $deposit);
125 8
        });
126
    }
127
128
    /**
129
     * This method ignores errors that occur when transferring funds
130
     *
131
     * @param Wallet $wallet
132
     * @param int $amount
133
     * @param array|null $meta
134
     * @return null|Transfer
135
     */
136 2
    public function safeTransfer(Wallet $wallet, int $amount, ?array $meta = null): ?Transfer
137
    {
138
        try {
139 2
            return $this->transfer($wallet, $amount, $meta);
140 2
        } catch (\Throwable $throwable) {
141 2
            return null;
142
        }
143
    }
144
145
    /**
146
     * the forced transfer is needed when the user does not have the money and we drive it.
147
     * Sometimes you do. Depends on business logic.
148
     *
149
     * @param Wallet $wallet
150
     * @param int $amount
151
     * @param array|null $meta
152
     * @return Transfer
153
     */
154 4
    public function forceTransfer(Wallet $wallet, int $amount, ?array $meta = null): Transfer
155
    {
156
        return DB::transaction(function() use ($amount, $wallet, $meta) {
157 4
            $fee = Tax::fee($wallet, $amount);
158 4
            $withdraw = $this->forceWithdraw($amount + $fee, $meta);
159 4
            $deposit = $wallet->deposit($amount, $meta);
160 4
            return $this->assemble($wallet, $withdraw, $deposit);
161 4
        });
162
    }
163
164
    /**
165
     * this method adds a new transfer to the transfer table
166
     *
167
     * @param Wallet $wallet
168
     * @param Transaction $withdraw
169
     * @param Transaction $deposit
170
     * @return Transfer
171
     * @throws
172
     */
173 9
    protected function assemble(Wallet $wallet, Transaction $withdraw, Transaction $deposit): Transfer
174
    {
175
        /**
176
         * @var Model $wallet
177
         */
178 9
        return \app(config('wallet.transfer.model'))->create([
0 ignored issues
show
Bug introduced by
The method create() does not exist on Illuminate\Foundation\Application. ( Ignorable by Annotation )

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

178
        return \app(config('wallet.transfer.model'))->/** @scrutinizer ignore-call */ create([

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
179 9
            'deposit_id' => $deposit->getKey(),
180 9
            'withdraw_id' => $withdraw->getKey(),
181 9
            'from_type' => $this->getMorphClass(),
0 ignored issues
show
Bug introduced by
It seems like getMorphClass() 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

181
            'from_type' => $this->/** @scrutinizer ignore-call */ getMorphClass(),
Loading history...
182 9
            'from_id' => $this->getKey(),
0 ignored issues
show
Bug introduced by
It seems like getKey() 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

182
            'from_id' => $this->/** @scrutinizer ignore-call */ getKey(),
Loading history...
183 9
            'to_type' => $wallet->getMorphClass(),
184 9
            'to_id' => $wallet->getKey(),
185 9
            'fee' => $withdraw->amount - $deposit->amount,
186 9
            'uuid' => Uuid::uuid4()->toString(),
187
        ]);
188
    }
189
190
    /**
191
     * this method adds a new transaction to the translation table
192
     *
193
     * @param int $amount
194
     * @param array|null $meta
195
     * @param bool $confirmed
196
     * @return Transaction
197
     * @throws
198
     */
199 15
    protected function change(int $amount, ?array $meta, bool $confirmed): Transaction
200
    {
201
        return DB::transaction(function() use ($amount, $meta, $confirmed) {
202
203 15
            if ($this instanceof WalletModel) {
204
                $payable = $this->holder;
205
                $wallet = $this;
206
            } else {
207 15
                $payable = $this;
208 15
                $wallet = $this->wallet;
209
            }
210
211 15
            if ($confirmed) {
212 15
                $this->addBalance($wallet, $amount);
213
            }
214
215 15
            return $this->transactions()->create([
216 15
                'type' => $amount > 0 ? 'deposit' : 'withdraw',
217 15
                'payable_type' => $payable->getMorphClass(),
218 15
                'payable_id' => $payable->getKey(),
219 15
                'wallet_id' => $wallet->getKey(),
220 15
                'uuid' => Uuid::uuid4()->toString(),
221 15
                'confirmed' => $confirmed,
222 15
                'amount' => $amount,
223 15
                'meta' => $meta,
224
            ]);
225 15
        });
226
    }
227
228
    /**
229
     * all user actions on wallets will be in this method
230
     *
231
     * @return MorphMany
232
     */
233 15
    public function transactions(): MorphMany
234
    {
235 15
        return $this->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

235
        return $this->/** @scrutinizer ignore-call */ morphMany(config('wallet.transaction.model'), 'payable');
Loading history...
236
    }
237
238
    /**
239
     * the transfer table is used to confirm the payment
240
     * this method receives all transfers
241
     *
242
     * @return MorphMany
243
     */
244 4
    public function transfers(): MorphMany
245
    {
246 4
        return $this->morphMany(config('wallet.transfer.model'), 'from');
247
    }
248
249
    /**
250
     * Get default Wallet
251
     * this method is used for Eager Loading
252
     *
253
     * @return MorphOne|WalletModel
254
     */
255 19
    public function wallet(): MorphOne
256
    {
257 19
        return $this->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

257
        return $this->/** @scrutinizer ignore-call */ morphOne(config('wallet.wallet.model'), 'holder')
Loading history...
258 19
            ->withDefault([
259 19
                'name' => config('wallet.wallet.default.name'),
260 19
                'slug' => config('wallet.wallet.default.slug'),
261 19
                'balance' => 0,
262
            ]);
263
    }
264
265
    /**
266
     * Magic laravel framework method, makes it
267
     *  possible to call property balance
268
     *
269
     * Example:
270
     *  $user1 = User::first()->load('wallet');
271
     *  $user2 = User::first()->load('wallet');
272
     *
273
     * Without static:
274
     *  var_dump($user1->balance, $user2->balance); // 100 100
275
     *  $user1->deposit(100);
276
     *  $user2->deposit(100);
277
     *  var_dump($user1->balance, $user2->balance); // 200 200
278
     *
279
     * With static:
280
     *  var_dump($user1->balance, $user2->balance); // 100 100
281
     *  $user1->deposit(100);
282
     *  var_dump($user1->balance); // 200
283
     *  $user2->deposit(100);
284
     *  var_dump($user2->balance); // 300
285
     *
286
     * @return int
287
     * @throws
288
     */
289 19
    public function getBalanceAttribute(): int
290
    {
291 19
        if ($this instanceof WalletModel) {
292 19
            $this->exists or $this->save();
293 19
            if (!WalletProxy::has($this->getKey())) {
294 19
                WalletProxy::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...
295
            }
296
297 19
            return WalletProxy::get($this->getKey());
298
        }
299
300 19
        return $this->wallet->balance;
301
    }
302
303
    /**
304
     * This method automatically updates the balance in the
305
     * database and the project statics
306
     *
307
     * @param WalletModel $wallet
308
     * @param int $amount
309
     * @return bool
310
     */
311 15
    protected function addBalance(WalletModel $wallet, int $amount): bool
312
    {
313 15
        $newBalance = $this->getBalanceAttribute() + $amount;
314 15
        $wallet->balance = $newBalance;
315
316
        return
317
            // update database wallet
318 15
            $wallet->save() &&
319
320
            // update static wallet
321 15
            WalletProxy::set($wallet->getKey(), $newBalance);
322
    }
323
324
}
325