Completed
Push — master ( 2e9d4d...4e36b1 )
by Scott
02:42
created

Discount::scopeIsNotExpired()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
124
     * @return [type]        [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
125
     */
126
    public function scopeIsNotExpired($query)
127
    {
128
        return $query->where(function($discount) {
129
            return $discount->whereNull('end_at')
130
                ->orWhere('end_at', '>', (string) Carbon::now());
131
        });
132
    }
133
134
    /**
135
     * This exists to makes statuses sortable by assigning them a value.
136
     *
137
     * Expired  0
138
     * Running  1
139
     * Upcoming 2
140
     *
141
     * @param  \October\Rain\Database\Builder   $query
142
     * @return \October\Rain\Database\Builder
143
     */
144
    public function scopeSelectStatus($query)
145
    {
146
        $grammar = $query->getQuery()->getGrammar();
147
        $start_at = $grammar->wrap($this->table.'.start_at');
148
        $end_at = $grammar->wrap($this->table.'.end_at');
149
        $now = Carbon::now();
150
151
        $subquery = 'CASE '.
152
            "WHEN ({$end_at} IS NOT NULL AND {$end_at} < '{$now}') THEN 0 ".
153
            "WHEN ({$start_at} IS NOT NULL AND {$start_at} > '{$now}') THEN 2 ".
154
            'ELSE 1 '.
155
        'END';
156
157
        return $query->selectSubquery($subquery, 'status');
158
    }
159
160
    /**
161
     * Set the discount amount.
162
     *
163
     * @return  void
164
     */
165
    public function setAmount()
166
    {
167
        $exact = $this->getOriginalPurgeValue('amount_exact');
168
        $percentage = $this->getOriginalPurgeValue('amount_percentage');
169
170
        $this->amount = $this->is_percentage
171
            ? $percentage
172
            : $exact;
173
    }
174
175
    /**
176
     * Ensure the start and end dates are valid.
177
     *
178
     * @return void
179
     */
180
    public function validateDates()
181
    {
182
        // Start date must be after the end date
183
        if ($this->start_at !== null &&
184
            $this->end_at !== null &&
185
            $this->start_at >= $this->end_at) {
186
            Flash::error(Lang::get('bedard.shop::lang.discounts.form.start_at_invalid'));
187
            throw new ModelException($this);
188
        }
189
    }
190
}
191