Completed
Push — master ( 76a437...dacfe4 )
by Scott
02:32
created

CartItem::beforeSave()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php namespace Bedard\Shop\Models;
2
3
use Model;
4
5
/**
6
 * CartItem Model.
7
 */
8
class CartItem extends Model
9
{
10
    use \October\Rain\Database\Traits\SoftDelete;
11
12
    /**
13
     * @var string The database table used by the model.
14
     */
15
    public $table = 'bedard_shop_cart_items';
16
17
    /**
18
     * @var array Default attributes
19
     */
20
    public $attributes = [
21
        'quantity' => 0,
22
    ];
23
24
    /**
25
     * @var array Attribute casting.
26
     */
27
    protected $casts = [
28
        'id' => 'integer',
29
        'cart_id' => 'integer',
30
        'inventory_id' => 'integer',
31
        'quantity' => 'integer',
32
    ];
33
34
    /**
35
     * @var array Date fields
36
     */
37
    protected $dates = ['deleted_at'];
38
39
    /**
40
     * @var array Guarded fields
41
     */
42
    protected $guarded = ['*'];
43
44
    /**
45
     * @var array Fillable fields
46
     */
47
    protected $fillable = [
48
        'cart_id',
49
        'inventory_id',
50
        'quantity',
51
    ];
52
53
    /**
54
     * @var array Relations
55
     */
56
    public $belongsTo = [
57
        'cart' => [
58
            'Bedard\Shop\Models\Cart',
59
        ],
60
        'inventory' => [
61
            'Bedard\Shop\Models\Inventory',
62
        ],
63
    ];
64
65
    /**
66
     * @var array Touch parent timestamps
67
     */
68
    protected $touches = [
69
        'cart',
70
    ];
71
72
    /**
73
     * Before save.
74
     *
75
     * @return void
76
     */
77
    public function beforeSave()
78
    {
79
        $this->validateQuantity();
80
    }
81
82
    protected function validateQuantity()
83
    {
84
        if ($this->quantity < 0) {
85
            $this->quantity = 0;
86
        }
87
        
88
        if ($this->quantity > $this->inventory->quantity) {
89
            $this->quantity = $this->inventory->quantity;
90
        }
91
    }
92
}
93