Completed
Push — master ( 20c7c7...fa6eea )
by Scott
02:26
created

Promotion::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
 * Promotion Model.
7
 */
8
class Promotion extends Model
9
{
10
    use \Bedard\Shop\Traits\StartEndable,
11
        \Bedard\Shop\Traits\Timeable,
12
        \October\Rain\Database\Traits\Purgeable,
13
        \October\Rain\Database\Traits\Validation;
14
15
    /**
16
     * @var string The database table used by the model.
17
     */
18
    public $table = 'bedard_shop_promotions';
19
20
    /**
21
     * @var array Default attributes
22
     */
23
    public $attributes = [
24
        'amount' => 0,
25
        'amount_exact' => 0,
26
        'amount_percentage' => 0,
27
        'is_percentage' => true,
28
    ];
29
30
    /**
31
     * @var array Guarded fields
32
     */
33
    protected $guarded = ['*'];
34
35
    /**
36
     * @var array Fillable fields
37
     */
38
    protected $fillable = [
39
        'amount_exact',
40
        'amount_percentage',
41
        'amount',
42
        'is_percentage',
43
        'message',
44
        'minimum_cart_value',
45
        'name',
46
    ];
47
48
    /**
49
     * @var array Purgeable vields
50
     */
51
    protected $purgeable = [
52
        'amount_exact',
53
        'amount_percentage',
54
    ];
55
56
    /**
57
     * @var  array Validation rules
58
     */
59
    public $rules = [
60
        'end_at' => 'date',
61
        'name' => 'required',
62
        'start_at' => 'date',
63
        'amount_exact' => 'numeric|min:0',
64
        'amount_percentage' => 'numeric|min:0|max:100',
65
    ];
66
67
    /**
68
     * Before save.
69
     *
70
     * @return void
71
     */
72
    public function beforeSave()
73
    {
74
        $this->setAmount();
75
    }
76
77
    /**
78
     * Filter form fields.
79
     *
80
     * @param  object   $fields
81
     * @return void
82
     */
83
    public function filterFields($fields)
84
    {
85
        $fields->amount_exact->hidden = $this->is_percentage;
86
        $fields->amount_percentage->hidden = ! $this->is_percentage;
87
    }
88
89
    /**
90
     * Set the promotion amount.
91
     *
92
     * @return  void
93
     */
94 View Code Duplication
    public function setAmount()
95
    {
96
        $exact = $this->getOriginalPurgeValue('amount_exact');
97
        $percentage = $this->getOriginalPurgeValue('amount_percentage');
98
99
        $this->amount = $this->is_percentage
100
            ? $percentage
101
            : $exact;
102
    }
103
}
104