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

Wallet::calculateBalance()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 8
nc 1
nop 0
dl 0
loc 12
ccs 0
cts 9
cp 0
crap 2
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\BelongsToMany;
11
12
/**
13
 * Class Wallet
14
 * @package Bavix\Wallet\Models
15
 * @property int $balance
16
 * @property \Bavix\Wallet\Interfaces\Wallet $holder
17
 */
18
class Wallet extends Model implements Customer, WalletFloat
19
{
20
21
    use CanBePaidFloat;
22
23
    /**
24
     * @var array
25
     */
26
    protected $fillable = [
27
        'holder_type',
28
        'holder_id',
29
        'name',
30
        'slug',
31
        'description',
32
        'balance',
33
    ];
34
35
    /**
36
     * @var array
37
     */
38
    protected $casts = [
39
        'balance' => 'int',
40
    ];
41
42
    /**
43
     * @return string
44
     */
45 21
    public function getTable(): string
46
    {
47 21
        if (!$this->table) {
48 21
            $this->table = \config('wallet.wallet.table');
49
        }
50
51 21
        return parent::getTable();
52
    }
53
54
    /**
55
     * @return bool
56
     */
57
    public function calculateBalance(): bool
58
    {
59
        $this->getBalanceAttribute();
60
        $balance = $this->transactions()
61
            ->where('wallet_id', $this->getKey())
62
            ->where('confirmed', true)
63
            ->sum('amount');
64
65
        WalletProxy::set($this->getKey(), $balance);
66
        $this->attributes['balance'] = $balance;
67
68
        return $this->save();
69
    }
70
71
    /**
72
     * @return BelongsToMany
73
     */
74
    public function holder(): BelongsToMany
75
    {
76
        return $this->belongsToMany('holder');
77
    }
78
79
}
80