Completed
Push — master ( 4553c1...3838fd )
by Scott
02:42
created

Product::saveBasePrice()   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 0
1
<?php namespace Bedard\Shop\Models;
2
3
use DB;
4
use Model;
5
use Queue;
6
7
/**
8
 * Product Model.
9
 */
10
class Product extends Model
11
{
12
    use \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_products';
19
20
    /**
21
     * @var array Default attributes
22
     */
23
    public $attributes = [
24
        'base_price' => 0,
25
    ];
26
27
    /**
28
     * @var array Guarded fields
29
     */
30
    protected $guarded = ['*'];
31
32
    /**
33
     * @var array Fillable fields
34
     */
35
    protected $fillable = [
36
        'name',
37
        'base_price',
38
        'slug',
39
    ];
40
41
    /**
42
     * @var array Purgeable fields
43
     */
44
    public $purgeable = [
45
        'categoriesList',
46
    ];
47
48
    /**
49
     * @var array Relations
50
     */
51
    public $belongsToMany = [
52
        'categories' => [
53
            'Bedard\Shop\Models\Category',
54
            'table' => 'bedard_shop_category_product',
55
            'conditions' => 'is_inherited = 0',
56
        ],
57
        'discounts' => [
58
            'Bedard\Shop\Models\Discount',
59
            'table' => 'bedard_shop_discount_product',
60
        ],
61
    ];
62
63
    public $hasMany = [
64
        'prices' => [
65
            'Bedard\Shop\Models\Price',
66
            'delete' => true,
67
        ],
68
    ];
69
70
    /**
71
     * @var array Validation
72
     */
73
    public $rules = [
74
        'name' => 'required',
75
        'base_price' => 'required|numeric|min:0',
76
        'slug' => 'required|unique:bedard_shop_products',
77
    ];
78
79
    /**
80
     * After save.
81
     *
82
     * @return void
83
     */
84
    public function afterSave()
85
    {
86
        $this->saveBasePrice();
87
        $this->saveCategoryRelationships();
88
    }
89
90
    /**
91
     * Attach a product to it's inherited categories.
92
     *
93
     * @param  array|null $categoryIds
94
     * @return void
95
     */
96
    public function attachInheritedCategories(array $categoryIds = null)
97
    {
98
        if ($categoryIds === null) {
99
            $categoryIds = $this->categories->lists('id');
100
        }
101
102
        foreach (Category::isParentOf($categoryIds)->lists('id') as $parentId) {
103
            $this->categories()->attach($parentId, ['is_inherited' => true]);
104
        }
105
    }
106
107
    /**
108
     * Detach a product from it's inherited categories.
109
     *
110
     * @return void
111
     */
112
    public function detachInheritedCategories()
113
    {
114
        DB::table('bedard_shop_category_product')
115
            ->where('product_id', $this->id)
116
            ->where('is_inherited', 1)
117
            ->delete();
118
    }
119
120
    /**
121
     * Get the categories options.
122
     *
123
     * @return array
124
     */
125
    public function getCategoriesListOptions()
126
    {
127
        return Category::orderBy('name')->lists('name', 'id');
128
    }
129
130
    /**
131
     * Get the categories that are directly related to this product.
132
     *
133
     * @return void
134
     */
135
    public function getCategoriesListAttribute()
136
    {
137
        return $this->categories()->lists('id');
138
    }
139
140
    /**
141
     * Update of create the related base price model.
142
     *
143
     * @return void
144
     */
145
    public function saveBasePrice()
146
    {
147
        Price::updateOrCreate(
148
            ['product_id' => $this->id, 'discount_id' => null],
149
            ['price' => $this->base_price]
150
        );
151
    }
152
153
    /**
154
     * Sync the categories checkboxlist with the category relationship.
155
     *
156
     * @return void
157
     */
158
    public function saveCategoryRelationships()
159
    {
160
        $categoryIds = $this->getOriginalPurgeValue('categoriesList');
161
162
        if (is_array($categoryIds)) {
163
            $this->categories()->sync($categoryIds);
164
            $this->syncInheritedCategories($categoryIds);
165
        }
166
    }
167
168
    /**
169
     * Sync the inherited categories of all products.
170
     *
171
     * @return void
172
     */
173
    public static function syncAllInheritedCategories()
174
    {
175
        foreach (self::lists('id') as $id) {
176
            Queue::push(function ($job) use ($id) {
177
                Product::findOrFail($id)->syncInheritedCategories();
178
                $job->delete();
179
            });
180
        }
181
    }
182
183
    /**
184
     * Sync a product with it's inherited categories.
185
     *
186
     * @param  array|null $categoryIds
187
     * @return void
188
     */
189
    public function syncInheritedCategories(array $categoryIds = null)
190
    {
191
        $this->detachInheritedCategories();
192
        $this->attachInheritedCategories($categoryIds);
193
    }
194
}
195