Completed
Push — master ( b2dc93...6950e4 )
by Scott
03:20
created

Discount::validateDates()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 10
rs 9.2
cc 4
eloc 6
nc 2
nop 0
1
<?php namespace Bedard\Shop\Models;
2
3
use Flash;
4
use Lang;
5
use Model;
6
use October\Rain\Database\ModelException;
7
8
/**
9
 * Discount Model.
10
 */
11
class Discount extends Model
12
{
13
    use \October\Rain\Database\Traits\Purgeable,
14
        \October\Rain\Database\Traits\Validation;
15
16
    /**
17
     * @var string The database table used by the model.
18
     */
19
    public $table = 'bedard_shop_discounts';
20
21
    /**
22
     * @var array Default attributes
23
     */
24
    public $attributes = [
25
        'is_percentage' => true,
26
    ];
27
28
    /**
29
     * @var array Attribute casting
30
     */
31
    protected $casts = [
32
        //
33
    ];
34
35
    /**
36
     * @var array Date casting
37
     */
38
    protected $dates = [
39
        'end_at',
40
        'start_at',
41
    ];
42
43
    /**
44
     * @var array Guarded fields
45
     */
46
    protected $guarded = ['*'];
47
48
    /**
49
     * @var array Fillable fields
50
     */
51
    protected $fillable = [
52
        'amount_exact',
53
        'amount_percentage',
54
        'end_at',
55
        'is_percentage',
56
        'name',
57
        'start_at',
58
    ];
59
60
    /**
61
     * @var array Purgeable vields
62
     */
63
    protected $purgeable = [
64
        'amount_exact',
65
        'amount_percentage',
66
    ];
67
68
    /**
69
     * @var array Relations
70
     */
71
    public $hasMany = [];
72
    public $morphMany = [];
73
74
    /**
75
     * @var  array Validation rules
76
     */
77
    public $rules = [
78
        'end_at' => 'date',
79
        'name' => 'required',
80
        'start_at' => 'date',
81
    ];
82
83
    /**
84
     * After validate.
85
     *
86
     * @return void
87
     */
88
    public function afterValidate()
89
    {
90
        $this->validateDates();
91
    }
92
93
    /**
94
     * Filter form fields.
95
     *
96
     * @param  object   $fields
97
     * @return void
98
     */
99
    public function filterFields($fields)
100
    {
101
        $fields->amount_exact->hidden = $this->is_percentage;
102
        $fields->amount_percentage->hidden = ! $this->is_percentage;
103
    }
104
105
    /**
106
     * Ensure the start and end dates are valid
107
     *
108
     * @return void
109
     */
110
    public function validateDates()
111
    {
112
        // Start date must be after the end date
113
        if ($this->start_at !== null &&
114
            $this->end_at !== null &&
115
            $this->start_at >= $this->end_at) {
116
            Flash::error(Lang::get('bedard.shop::lang.discounts.form.start_at_invalid'));
117
            throw new ModelException($this);
118
        }
119
    }
120
}
121