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

Wallet::calculateBalance()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 0
dl 0
loc 11
ccs 8
cts 8
cp 1
crap 1
rs 10
c 0
b 0
f 0
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 31
    public function getTable(): string
48
    {
49 31
        if (!$this->table) {
50 31
            $this->table = \config('wallet.wallet.table');
51
        }
52
53 31
        return parent::getTable();
54
    }
55
56
    /**
57
     * @param string $name
58
     * @return void
59
     */
60 29
    public function setNameAttribute(string $name): void
61
    {
62 29
        $this->attributes['name'] = $name;
63 29
        $this->attributes['slug'] = Str::slug($name);
64 29
    }
65
66
    /**
67
     * @return bool
68
     */
69 1
    public function calculateBalance(): bool
70
    {
71 1
        $balance = $this->holder->transactions()
72 1
            ->where('wallet_id', $this->getKey())
73 1
            ->where('confirmed', true)
74 1
            ->sum('amount');
75
76 1
        WalletProxy::set($this->getKey(), $balance);
77 1
        $this->attributes['balance'] = $balance;
78
79 1
        return $this->save();
80
    }
81
82
    /**
83
     * @return MorphTo
84
     */
85 6
    public function holder(): MorphTo
86
    {
87 6
        return $this->morphTo();
88
    }
89
90
}
91