Completed
Pull Request — master (#14)
by Бабичев
03:24
created

HasWallet::transactions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
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 24
    private function checkAmount(int $amount): void
40
    {
41 24
        if ($amount < 0) {
42 3
            throw new AmountInvalid(trans('wallet::errors.price_positive'));
43
        }
44 21
    }
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 21
    public function forceWithdraw(int $amount, ?array $meta = null, bool $confirmed = true): Transaction
56
    {
57 21
        $this->checkAmount($amount);
58 21
        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 24
    public function deposit(int $amount, ?array $meta = null, bool $confirmed = true): Transaction
71
    {
72 24
        $this->checkAmount($amount);
73 21
        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 26
    public function withdraw(int $amount, ?array $meta = null, bool $confirmed = true): Transaction
86
    {
87 26
        if (!$this->balance) {
88 13
            throw new BalanceIsEmpty(trans('wallet::errors.wallet_empty'));
89
        }
90
91 20
        if (!$this->canWithdraw($amount)) {
92
            throw new InsufficientFunds(trans('wallet::errors.insufficient_funds'));
93
        }
94
95 20
        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 20
    public function canWithdraw(int $amount): bool
105
    {
106 20
        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 10
    public function transfer(Wallet $wallet, int $amount, ?array $meta = null): Transfer
119
    {
120
        return DB::transaction(function() use ($amount, $wallet, $meta) {
121 10
            $fee = Tax::fee($wallet, $amount);
122 10
            $withdraw = $this->withdraw($amount + $fee, $meta);
123 10
            $deposit = $wallet->deposit($amount, $meta);
124 10
            return $this->assemble($wallet, $withdraw, $deposit);
125 10
        });
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 3
    public function safeTransfer(Wallet $wallet, int $amount, ?array $meta = null): ?Transfer
137
    {
138
        try {
139 3
            return $this->transfer($wallet, $amount, $meta);
140 3
        } catch (\Throwable $throwable) {
141 3
            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 5
    public function forceTransfer(Wallet $wallet, int $amount, ?array $meta = null): Transfer
155
    {
156
        return DB::transaction(function() use ($amount, $wallet, $meta) {
157 5
            $fee = Tax::fee($wallet, $amount);
158 5
            $withdraw = $this->forceWithdraw($amount + $fee, $meta);
159 5
            $deposit = $wallet->deposit($amount, $meta);
160 5
            return $this->assemble($wallet, $withdraw, $deposit);
161 5
        });
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 11
    protected function assemble(Wallet $wallet, Transaction $withdraw, Transaction $deposit): Transfer
174
    {
175
        /**
176
         * @var Model $wallet
177
         */
178 11
        return \app('bavix.wallet::transfer')->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('bavix.wallet::transfer')->/** @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 11
            'deposit_id' => $deposit->getKey(),
180 11
            'withdraw_id' => $withdraw->getKey(),
181 11
            '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 11
            '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 11
            'to_type' => $wallet->getMorphClass(),
184 11
            'to_id' => $wallet->getKey(),
185 11
            'fee' => $withdraw->amount - $deposit->amount,
186 11
            '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 21
    protected function change(int $amount, ?array $meta, bool $confirmed): Transaction
200
    {
201
        return DB::transaction(function() use ($amount, $meta, $confirmed) {
202
203 21
            if ($this instanceof WalletModel) {
204 5
                $payable = $this->holder;
205 5
                $wallet = $this;
206
            } else {
207 16
                $payable = $this;
208 16
                $wallet = $this->wallet;
209
            }
210
211 21
            if ($confirmed) {
212 21
                $this->addBalance($wallet, $amount);
213
            }
214
215 21
            return $payable->transactions()->create([
216 21
                'type' => $amount > 0 ? 'deposit' : 'withdraw',
217 21
                'wallet_id' => $wallet->getKey(),
218 21
                'uuid' => Uuid::uuid4()->toString(),
219 21
                'confirmed' => $confirmed,
220 21
                'amount' => $amount,
221 21
                'meta' => $meta,
222
            ]);
223 21
        });
224
    }
225
226
    /**
227
     * all user actions on wallets will be in this method
228
     *
229
     * @return MorphMany
230
     */
231 21
    public function transactions(): MorphMany
232
    {
233 21
        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

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

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