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

HasWallet::checkAmount()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 1
dl 0
loc 4
ccs 3
cts 3
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\Interfaces\Wallet;
9
use Bavix\Wallet\Models\Transaction;
10
use Bavix\Wallet\Models\Transfer;
11
use Bavix\Wallet\Models\Wallet as WalletModel;
12
use Bavix\Wallet\Services\ProxyService;
13
use Bavix\Wallet\Services\WalletService;
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 input means in the system
35
     *
36
     * @param int $amount
37
     * @param array|null $meta
38
     * @param bool $confirmed
39
     *
40
     * @return Transaction
41
     */
42 30
    public function deposit(int $amount, ?array $meta = null, bool $confirmed = true): Transaction
43
    {
44 30
        $this->checkAmount($amount);
45 27
        return $this->change(Transaction::TYPE_DEPOSIT, $amount, $meta, $confirmed);
46
    }
47
48
    /**
49
     * The amount of checks for errors
50
     *
51
     * @param int $amount
52
     * @throws
53
     */
54 30
    private function checkAmount(int $amount): void
55
    {
56 30
        if ($amount < 0) {
57 3
            throw new AmountInvalid(trans('wallet::errors.price_positive'));
0 ignored issues
show
Bug introduced by
It seems like trans('wallet::errors.price_positive') can also be of type array; however, parameter $message of Bavix\Wallet\Exceptions\...tInvalid::__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

57
            throw new AmountInvalid(/** @scrutinizer ignore-type */ trans('wallet::errors.price_positive'));
Loading history...
58
        }
59 27
    }
60
61
    /**
62
     * this method adds a new transaction to the translation table
63
     *
64
     * @param string $type
65
     * @param int $amount
66
     * @param array|null $meta
67
     * @param bool $confirmed
68
     * @return Transaction
69
     * @throws
70
     */
71 27
    protected function change(string $type, int $amount, ?array $meta, bool $confirmed): Transaction
72
    {
73
        return DB::transaction(function () use ($type, $amount, $meta, $confirmed) {
74
75 27
            $wallet = $this;
76 27
            if (!($this instanceof WalletModel)) {
77 22
                $wallet = $this->wallet;
78
            }
79
80 27
            if ($confirmed) {
81 27
                $this->addBalance($wallet, $amount);
82
            }
83
84 27
            return $this->transactions()->create([
85 27
                'type' => $type,
86 27
                'wallet_id' => $wallet->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

86
                'wallet_id' => $wallet->/** @scrutinizer ignore-call */ getKey(),
Loading history...
87 27
                'uuid' => Uuid::uuid4()->toString(),
88 27
                'confirmed' => $confirmed,
89 27
                'amount' => $amount,
90 27
                'meta' => $meta,
91
            ]);
92 27
        });
93
    }
94
95
    /**
96
     * This method automatically updates the balance in the
97
     * database and the project statics
98
     *
99
     * @param WalletModel $wallet
100
     * @param int $amount
101
     * @return bool
102
     */
103 27
    protected function addBalance(WalletModel $wallet, int $amount): bool
104
    {
105 27
        $newBalance = $this->getBalanceAttribute() + $amount;
106 27
        $wallet->balance = $newBalance;
107
108 27
        if ($wallet->save()) {
109 27
            $proxy = app(ProxyService::class);
110 27
            $proxy->set($wallet->getKey(), $newBalance);
0 ignored issues
show
Bug introduced by
It seems like $wallet->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

110
            $proxy->set(/** @scrutinizer ignore-type */ $wallet->getKey(), $newBalance);
Loading history...
111 27
            return true;
112
        }
113
114
        return false;
115
    }
116
117
    /**
118
     * Magic laravel framework method, makes it
119
     *  possible to call property balance
120
     *
121
     * Example:
122
     *  $user1 = User::first()->load('wallet');
123
     *  $user2 = User::first()->load('wallet');
124
     *
125
     * Without static:
126
     *  var_dump($user1->balance, $user2->balance); // 100 100
127
     *  $user1->deposit(100);
128
     *  $user2->deposit(100);
129
     *  var_dump($user1->balance, $user2->balance); // 200 200
130
     *
131
     * With static:
132
     *  var_dump($user1->balance, $user2->balance); // 100 100
133
     *  $user1->deposit(100);
134
     *  var_dump($user1->balance); // 200
135
     *  $user2->deposit(100);
136
     *  var_dump($user2->balance); // 300
137
     *
138
     * @return int
139
     * @throws
140
     */
141 37
    public function getBalanceAttribute(): int
142
    {
143 37
        if ($this instanceof WalletModel) {
144 37
            $this->exists or $this->save();
145 37
            $proxy = app(ProxyService::class);
146 37
            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

146
            if (!$proxy->has(/** @scrutinizer ignore-type */ $this->getKey())) {
Loading history...
147 37
                $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

147
                $proxy->set(/** @scrutinizer ignore-type */ $this->getKey(), (int)($this->attributes['balance'] ?? 0));
Loading history...
148
            }
149
150 37
            return $proxy[$this->getKey()];
151
        }
152
153 37
        return $this->wallet->balance;
154
    }
155
156
    /**
157
     * all user actions on wallets will be in this method
158
     *
159
     * @return MorphMany
160
     */
161 27
    public function transactions(): MorphMany
162
    {
163 27
        return ($this instanceof WalletModel ? $this->holder : $this)
164 27
            ->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

164
            ->/** @scrutinizer ignore-call */ morphMany(config('wallet.transaction.model'), 'payable');
Loading history...
165
    }
166
167
    /**
168
     * This method ignores errors that occur when transferring funds
169
     *
170
     * @param Wallet $wallet
171
     * @param int $amount
172
     * @param array|null $meta
173
     * @param string $status
174
     * @return null|Transfer
175
     */
176 3
    public function safeTransfer(Wallet $wallet, int $amount, ?array $meta = null, string $status = Transfer::STATUS_TRANSFER): ?Transfer
177
    {
178
        try {
179 3
            return $this->transfer($wallet, $amount, $meta, $status);
180 3
        } catch (\Throwable $throwable) {
181 3
            return null;
182
        }
183
    }
184
185
    /**
186
     * A method that transfers funds from host to host
187
     *
188
     * @param Wallet $wallet
189
     * @param int $amount
190
     * @param array|null $meta
191
     * @param string $status
192
     * @return Transfer
193
     * @throws
194
     */
195 14
    public function transfer(Wallet $wallet, int $amount, ?array $meta = null, string $status = Transfer::STATUS_TRANSFER): Transfer
196
    {
197
        return DB::transaction(function () use ($amount, $wallet, $meta, $status) {
198 14
            $fee = app(WalletService::class)
199 14
                ->fee($wallet, $amount);
200
201 14
            $withdraw = $this->withdraw($amount + $fee, $meta);
202 14
            $deposit = $wallet->deposit($amount, $meta);
203 14
            return $this->assemble($wallet, $withdraw, $deposit, $status);
204 14
        });
205
    }
206
207
    /**
208
     * Withdrawals from the system
209
     *
210
     * @param int $amount
211
     * @param array|null $meta
212
     * @param bool $confirmed
213
     *
214
     * @return Transaction
215
     */
216 32
    public function withdraw(int $amount, ?array $meta = null, bool $confirmed = true): Transaction
217
    {
218 32
        if ($amount && !$this->balance) {
219 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

219
            throw new BalanceIsEmpty(/** @scrutinizer ignore-type */ trans('wallet::errors.wallet_empty'));
Loading history...
220
        }
221
222 26
        if (!$this->canWithdraw($amount)) {
223 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

223
            throw new InsufficientFunds(/** @scrutinizer ignore-type */ trans('wallet::errors.insufficient_funds'));
Loading history...
224
        }
225
226 25
        return $this->forceWithdraw($amount, $meta, $confirmed);
227
    }
228
229
    /**
230
     * Checks if you can withdraw funds
231
     *
232
     * @param int $amount
233
     * @return bool
234
     */
235 26
    public function canWithdraw(int $amount): bool
236
    {
237 26
        return $this->balance >= $amount;
238
    }
239
240
    /**
241
     * Forced to withdraw funds from system
242
     *
243
     * @param int $amount
244
     * @param array|null $meta
245
     * @param bool $confirmed
246
     *
247
     * @return Transaction
248
     */
249 26
    public function forceWithdraw(int $amount, ?array $meta = null, bool $confirmed = true): Transaction
250
    {
251 26
        $this->checkAmount($amount);
252 26
        return $this->change(Transaction::TYPE_WITHDRAW, -$amount, $meta, $confirmed);
253
    }
254
255
    /**
256
     * this method adds a new transfer to the transfer table
257
     *
258
     * @param Wallet $wallet
259
     * @param Transaction $withdraw
260
     * @param Transaction $deposit
261
     * @param string $status
262
     * @return Transfer
263
     * @throws
264
     */
265 16
    protected function assemble(Wallet $wallet, Transaction $withdraw, Transaction $deposit, string $status = Transfer::STATUS_PAID): Transfer
266
    {
267
        /**
268
         * @var Model $wallet
269
         */
270 16
        return \app('bavix.wallet::transfer')->create([
0 ignored issues
show
Bug introduced by
The method create() does not exist on Illuminate\Contracts\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

270
        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...
271 16
            'status' => $status,
272 16
            'deposit_id' => $deposit->getKey(),
273 16
            'withdraw_id' => $withdraw->getKey(),
274 16
            'from_type' => ($this instanceof WalletModel ? $this : $this->wallet)->getMorphClass(),
275 16
            'from_id' => ($this instanceof WalletModel ? $this : $this->wallet)->getKey(),
276 16
            'to_type' => $wallet->getMorphClass(),
277 16
            'to_id' => $wallet->getKey(),
278 16
            'fee' => \abs($withdraw->amount) - \abs($deposit->amount),
279 16
            'uuid' => Uuid::uuid4()->toString(),
280
        ]);
281
    }
282
283
    /**
284
     * the forced transfer is needed when the user does not have the money and we drive it.
285
     * Sometimes you do. Depends on business logic.
286
     *
287
     * @param Wallet $wallet
288
     * @param int $amount
289
     * @param array|null $meta
290
     * @param string $status
291
     * @return Transfer
292
     */
293 6
    public function forceTransfer(Wallet $wallet, int $amount, ?array $meta = null, string $status = Transfer::STATUS_TRANSFER): Transfer
294
    {
295
        return DB::transaction(function () use ($amount, $wallet, $meta, $status) {
296 6
            $fee = app(WalletService::class)
297 6
                ->fee($wallet, $amount);
298
299 6
            $withdraw = $this->forceWithdraw($amount + $fee, $meta);
300 6
            $deposit = $wallet->deposit($amount, $meta);
301 6
            return $this->assemble($wallet, $withdraw, $deposit, $status);
302 6
        });
303
    }
304
305
    /**
306
     * the transfer table is used to confirm the payment
307
     * this method receives all transfers
308
     *
309
     * @return MorphMany
310
     */
311 9
    public function transfers(): MorphMany
312
    {
313 9
        if (!($this instanceof WalletModel)) {
314 9
            return $this->wallet->transfers();
315
        }
316
317 9
        return $this->morphMany(config('wallet.transfer.model'), 'from');
318
    }
319
320
    /**
321
     * Get default Wallet
322
     * this method is used for Eager Loading
323
     *
324
     * @return MorphOne|WalletModel
325
     */
326 37
    public function wallet(): MorphOne
327
    {
328
        return $this
329 37
            ->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

329
            ->/** @scrutinizer ignore-call */ morphOne(config('wallet.wallet.model'), 'holder')
Loading history...
330 37
            ->where('slug', config('wallet.wallet.default.slug'))
331 37
            ->withDefault([
332 37
                'name' => config('wallet.wallet.default.name'),
333 37
                'slug' => config('wallet.wallet.default.slug'),
334 37
                'balance' => 0,
335
            ]);
336
    }
337
338
}
339