Passed
Push — master ( d27bd5...494f2f )
by Бабичев
03:09
created

Wallet   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 25
dl 0
loc 75
ccs 19
cts 19
cp 1
rs 10
c 0
b 0
f 0
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getTable() 0 7 2
A holder() 0 3 1
A setNameAttribute() 0 10 3
A calculateBalance() 0 11 1
1
<?php
2
3
namespace Bavix\Wallet\Models;
4
5
use Bavix\Wallet\Interfaces\Customer;
6
use Bavix\Wallet\Interfaces\WalletFloat;
7
use Bavix\Wallet\Traits\CanBePaidFloat;
8
use Bavix\Wallet\WalletProxy;
9
use Illuminate\Database\Eloquent\Model;
10
use Illuminate\Database\Eloquent\Relations\MorphTo;
11
use Illuminate\Support\Str;
12
13
/**
14
 * Class Wallet
15
 * @package Bavix\Wallet\Models
16
 * @property string $slug
17
 * @property int $balance
18
 * @property \Bavix\Wallet\Interfaces\Wallet $holder
19
 */
20
class Wallet extends Model implements Customer, WalletFloat
21
{
22
23
    use CanBePaidFloat;
0 ignored issues
show
introduced by
The trait Bavix\Wallet\Traits\CanBePaidFloat requires some properties which are not provided by Bavix\Wallet\Models\Wallet: $amount, $deposit
Loading history...
24
25
    /**
26
     * @var array
27
     */
28
    protected $fillable = [
29
        'holder_type',
30
        'holder_id',
31
        'name',
32
        'slug',
33
        'description',
34
        'balance',
35
    ];
36
37
    /**
38
     * @var array
39
     */
40
    protected $casts = [
41
        'balance' => 'int',
42
    ];
43
44
    /**
45
     * @return string
46
     */
47 36
    public function getTable(): string
48
    {
49 36
        if (!$this->table) {
50 36
            $this->table = \config('wallet.wallet.table');
51
        }
52
53 36
        return parent::getTable();
54
    }
55
56
    /**
57
     * @param string $name
58
     * @return void
59
     */
60 34
    public function setNameAttribute(string $name): void
61
    {
62 34
        $this->attributes['name'] = $name;
63
64
        /**
65
         * Must be updated only if the model does not exist
66
         *  or the slug is empty
67
         */
68 34
        if (!$this->exists && !\array_key_exists('slug', $this->attributes)) {
69 34
            $this->attributes['slug'] = Str::slug($name);
70
        }
71 34
    }
72
73
    /**
74
     * @return bool
75
     */
76 1
    public function calculateBalance(): bool
77
    {
78 1
        $balance = $this->transactions()
79 1
            ->where('wallet_id', $this->getKey())
80 1
            ->where('confirmed', true)
81 1
            ->sum('amount');
82
83 1
        WalletProxy::set($this->getKey(), $balance);
84 1
        $this->attributes['balance'] = $balance;
85
86 1
        return $this->save();
87
    }
88
89
    /**
90
     * @return MorphTo
91
     */
92 6
    public function holder(): MorphTo
93
    {
94 6
        return $this->morphTo();
95
    }
96
97
}
98