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

HasWallets::wallets()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 3
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Bavix\Wallet\Traits;
4
5
use Bavix\Wallet\Models\Wallet as WalletModel;
6
use Illuminate\Database\Eloquent\Relations\MorphMany;
7
use Illuminate\Support\Collection;
8
9
/**
10
 * Trait HasWallets
11
 * To use a trait, you must add HasWallet trait.
12
 *
13
 * @package Bavix\Wallet\Traits
14
 *
15
 * @property-read Collection|WalletModel[] $wallets
16
 */
17
trait HasWallets
18
{
19
20
    /**
21
     * The variable is used for the cache, so as not to request wallets many times.
22
     * WalletProxy keeps the money wallets in the memory to avoid errors when you
23
     * purchase/transfer, etc.
24
     *
25
     * @var array
26
     */
27
    private $_wallets = [];
28
29
    /**
30
     * method of obtaining all wallets
31
     *
32
     * @return MorphMany
33
     */
34
    public function wallets(): MorphMany
35
    {
36
        return $this->morphMany(config('wallet.wallet.model'), 'holder');
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

36
        return $this->/** @scrutinizer ignore-call */ morphMany(config('wallet.wallet.model'), 'holder');
Loading history...
37
    }
38
39
    /**
40
     * Get wallet by slug
41
     *
42
     *  $user->wallet->balance // 200
43
     *  or short recording $user->balance; // 200
44
     *
45
     *  $defaultSlug = config('wallet.wallet.default.slug');
46
     *  $user->getWallet($defaultSlug)->balance; // 200
47
     *
48
     *  $user->getWallet('usd')->balance; // 50
49
     *  $user->getWallet('rub')->balance; // 100
50
     *
51
     * @param string $slug
52
     * @return WalletModel|null
53
     */
54
    public function getWallet(string $slug): ?WalletModel
55
    {
56
        if (!\array_key_exists($slug, $this->_wallets)) {
57
            $this->_wallets[$slug] = $this->wallets()
58
                ->where('slug', $slug)
59
                ->first();
60
        }
61
62
        return $this->_wallets[$slug];
63
    }
64
65
}
66