ProductService::create()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 13
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 24
rs 9.8333
1
<?php
2
3
namespace Hideyo\Ecommerce\Framework\Services\Product;
4
 
5
use App\Product;
0 ignored issues
show
Bug introduced by
The type App\Product was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use Validator;
7
use File;
8
use Image;
9
use Hideyo\Ecommerce\Framework\Services\Product\Entity\ProductRepository;
10
use Hideyo\Ecommerce\Framework\Services\Shop\ShopFacade as ShopService;
11
use Hideyo\Ecommerce\Framework\Services\BaseService;
12
 
13
class ProductService extends BaseService
14
{
15
	public function __construct(ProductRepository $product)
16
	{
17
		$this->repo = $product;
0 ignored issues
show
Bug Best Practice introduced by
The property repo does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
18
        $this->storageImagePath = storage_path() .config('hideyo.storage_path'). "/product/";
0 ignored issues
show
Bug Best Practice introduced by
The property storageImagePath does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
19
        $this->publicImagePath = public_path() .config('hideyo.public_path'). "/product/";
0 ignored issues
show
Bug Best Practice introduced by
The property publicImagePath does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
20
21
	} 
22
23
24
 /**
25
     * The validation rules for the model.
26
     *
27
     * @param  integer  $productId id attribute model    
28
     * @return array
29
     */
30
    private function rules($productId = false, $attributes = false)
31
    {
32
        if (isset($attributes['seo'])) {
33
            $rules = array(
34
                'meta_title'                 => 'required|between:4,65',
35
                'meta_description'           => 'required|between:4,160',
36
            );
37
        } elseif (isset($attributes['product-combination'])) {
38
            $rules = array();
39
        } elseif (isset($attributes['price'])) {
40
            $rules = array(
41
                'discount_start_date' => 'nullable|date_format:d/m/Y',
42
                'discount_end_date' => 'nullable|date_format:d/m/Y'
43
            );
44
        } else {
45
            $rules = array(
46
                'title'                 => 'required|between:4,65|unique_with:'.$this->repo->getModel()->getTable().', shop_id',
47
                'amount'                => 'integer|required',
48
                'product_category_id'   => 'required|integer',
49
                'tax_rate_id'           => 'integer',
50
                'reference_code'      => 'required'
51
            );
52
            
53
            if ($productId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $productId of type false|integer is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
54
                $rules['title'] =   'required|between:4,65|unique_with:'.$this->repo->getModel()->getTable().', shop_id, '.$productId.' = id';
55
            }
56
        }
57
58
59
        return $rules;
60
    }
61
62
    public function createCopy(array $attributes, $productId)
0 ignored issues
show
Unused Code introduced by
The parameter $productId is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

62
    public function createCopy(array $attributes, /** @scrutinizer ignore-unused */ $productId)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
63
    {
64
        $attributes['shop_id'] = auth('hideyobackend')->user()->selected_shop_id;
0 ignored issues
show
Bug introduced by
Accessing selected_shop_id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
65
        $validator = Validator::make($attributes, $this->rules());
66
67
        if ($validator->fails()) {
68
            return $validator;
69
        }
70
   
71
        $attributes['modified_by_user_id'] = auth('hideyobackend')->user()->id;
0 ignored issues
show
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
72
        if (empty($attributes['discount_value'])) {
73
            $attributes['discount_value'] = null;
74
        }
75
76
        $this->getModel()->fill($attributes);
77
78
        $this->getModel()->save();
79
80
        if (isset($attributes['subcategories'])) {
81
            $this->getModel()->subcategories()->sync($attributes['subcategories']);
82
        }
83
                
84
        return $this->getModel();
85
    }
86
87
  
88
    public function create(array $attributes)
89
    {
90
        
91
        $attributes['shop_id'] = auth('hideyobackend')->user()->selected_shop_id;
0 ignored issues
show
Bug introduced by
Accessing selected_shop_id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
92
        $validator = Validator::make($attributes, $this->rules());
93
94
        if ($validator->fails()) {
95
            return $validator;
96
        }
97
   
98
        $attributes['modified_by_user_id'] = auth('hideyobackend')->user()->id;
0 ignored issues
show
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
99
        if (empty($attributes['discount_value'])) {
100
            $attributes['discount_value'] = null;
101
        }
102
103
        $this->getModel()->fill($attributes);
104
        $this->getModel()->save();
105
        if (isset($attributes['subcategories'])) {
106
            $this->getModel()->subcategories()->sync($attributes['subcategories']);
107
        }
108
        
109
        $this->getModel()->addAllToIndex();
110
111
        return $this->getModel();
112
    }
113
114
    public function createImage(array $attributes, $productId)
115
    {
116
        $userId = auth('hideyobackend')->user()->id;
0 ignored issues
show
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
117
        $shopId = auth('hideyobackend')->user()->selected_shop_id;
0 ignored issues
show
Bug introduced by
Accessing selected_shop_id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
118
        $shop = ShopService::find($shopId);
119
        $attributes['modified_by_user_id'] = $userId;
120
121
        $destinationPath = $this->storageImagePath.$productId;
122
        $attributes['user_id'] = $userId;
123
        $attributes['product_id'] = $productId;
124
125
        $rules = array(
126
            'file'=>'required|image|max:1000',
127
            'rank' => 'required'
128
        );
129
130
        foreach ($attributes['files'] as $file) {
131
132
            $attributes['file'] = $file;
133
            $validator = Validator::make($attributes, $rules);
134
135
            if ($validator->fails()) {
136
                return $validator;
137
            }
138
139
            $attributes['extension'] = $file->getClientOriginalExtension();
140
            $attributes['size'] = $file->getSize();
141
            $filename = str_replace(" ", "_", strtolower($file->getClientOriginalName()));
142
            $uploadSuccess = $file->move($destinationPath, $filename);
143
144
            if ($uploadSuccess) {
145
                $attributes['file'] = $filename;
146
                $attributes['path'] = $uploadSuccess->getRealPath();
147
                $file = $this->repo->getImageModel();
148
                $file->fill($attributes);
149
                $file->save();
150
                if ($shop->thumbnail_square_sizes) {
151
                    $sizes = explode(',', $shop->thumbnail_square_sizes);
152
                    if ($sizes) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $sizes of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
153
                        foreach ($sizes as $valueSize) {
154
                            $image = Image::make($uploadSuccess->getRealPath());
155
                            $explode = explode('x', $valueSize);
156
157
                            if ($image->width() >= $explode[0] and $image->height() >= $explode[1]) {
158
                                $image->resize($explode[0], $explode[1]);
159
                            }
160
161
                            if (!File::exists($this->publicImagePath.$valueSize."/".$productId."/")) {
162
                                File::makeDirectory($this->publicImagePath.$valueSize."/".$productId."/", 0777, true);
163
                            }
164
165
                            $image->interlace();
166
167
                            $image->save($this->publicImagePath.$valueSize."/".$productId."/".$filename);
168
                        }
169
                    }
170
                }
171
            } 
172
        }
173
174
        if (isset($attributes['productAttributes'])) {
175
            $file->relatedProductAttributes()->sync($attributes['productAttributes']);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $file seems to be defined by a foreach iteration on line 130. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
176
        }
177
178
        if (isset($attributes['attributes'])) {
179
            $this->model->relatedAttributes()->sync($attributes['attributes']);
0 ignored issues
show
Bug Best Practice introduced by
The property model does not exist on Hideyo\Ecommerce\Framewo...\Product\ProductService. Did you maybe forget to declare it?
Loading history...
180
        }
181
182
        $file->save();
183
        return $file;
184
    }
185
186
    public function refactorAllImagesByShopId($shopId)
187
    {
188
        $result = $this->getImageModel()->get();
189
        $shop = ShopService::find($shopId);
190
        foreach ($result as $productImage) {
191
            if ($shop->thumbnail_square_sizes) {
192
                $sizes = explode(',', $shop->thumbnail_square_sizes);
193
                if ($sizes) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $sizes of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
194
                    foreach ($sizes as $valueSize) {
195
                        if (!File::exists($this->publicImagePath.$valueSize."/".$productImage->product_id."/")) {
196
                            File::makeDirectory($this->publicImagePath.$valueSize."/".$productImage->product_id."/", 0777, true);
197
                        }
198
199
                        if (!File::exists($this->publicImagePath.$valueSize."/".$productImage->product_id."/".$productImage->file)) {
200
                            if (File::exists($this->storageImagePath.$productImage->product_id."/".$productImage->file)) {
201
                                $image = Image::make($this->storageImagePath.$productImage->product_id."/".$productImage->file);
202
                                $explode = explode('x', $valueSize);
203
                                $image->fit($explode[0], $explode[1]);
204
                            
205
                                $image->interlace();
206
207
                                $image->save($this->publicImagePath.$valueSize."/".$productImage->product_id."/".$productImage->file);
208
                            }
209
                        }
210
                    }
211
                }
212
            }
213
        }
214
    }
215
216
    public function updateById(array $attributes, $productId)
217
    {
218
        $attributes['shop_id'] = auth('hideyobackend')->user()->selected_shop_id;
0 ignored issues
show
Bug introduced by
Accessing selected_shop_id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
219
        $validator = Validator::make($attributes, $this->rules($productId, $attributes));
220
221
        if ($validator->fails()) {
222
            return $validator;
223
        }
224
225
        $attributes['modified_by_user_id'] = auth('hideyobackend')->user()->id;
0 ignored issues
show
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
226
        $model = $this->find($productId);
227
228
        $oldTitle = $model->title;
229
        $oldSlug = $model->slug;
230
        $oldProductCategoryId = $model->product_category_id;
231
        $oldProductCategorySlug = $model->productCategory->slug;
232
233
        if (empty($attributes['leading_atrribute_group_id'])) {
234
            $attributes['leading_atrribute_group_id'] = null;
235
        }
236
237
        if (empty($attributes['discount_value'])) {
238
            $attributes['discount_value'] = null;
239
        }
240
241
242
        if (count($attributes) > 0) {
243
            $model->fill($attributes);
244
            $model->subcategories()->sync(array());
245
            
246
            if (isset($attributes['subcategories'])) {
247
                $model->subcategories()->sync($attributes['subcategories']);
248
            }
249
250
            $model->save();
251
        }
252
253
        if (isset($attributes['title']) and isset($attributes['product_category_id'])) {
254
            if (($oldTitle != $attributes['title']) or ($oldProductCategoryId != $attributes['product_category_id'])) {
255
                $url = $model->shop->url.route('product.item', ['productId' => $model->id, 'productSlug' => $oldSlug, 'categorySlug' => $oldProductCategorySlug], null);
256
                if ($model->active) {
257
                    $this->redirect->destroyByUrl($url);
0 ignored issues
show
Bug Best Practice introduced by
The property redirect does not exist on Hideyo\Ecommerce\Framewo...\Product\ProductService. Did you maybe forget to declare it?
Loading history...
258
                }
259
                
260
                $newUrl = $model->shop->url.route('product.item', ['productId' => $model->id, 'productSlug' => $model->slug, 'categorySlug' => $model->productCategory->slug], null);
261
                $redirectResult = $this->redirect->create(array('active' => 1, 'url' => $url, 'redirect_url' => $newUrl, 'shop_id' => $model->shop_id));
0 ignored issues
show
Unused Code introduced by
The assignment to $redirectResult is dead and can be removed.
Loading history...
262
            }
263
        }
264
265
        if (!$model->active) {
266
            $url = $model->shop->url.route('product.item', ['productId' => $model->id, 'productSlug' => $model->slug, 'categorySlug' => $model->productCategory->slug], null);
267
            $productCategoryUrl = $model->shop->url.route('product-category', ['slug' => $model->productCategory->slug], null);
268
            $redirectResult = $this->redirect->create(array('active' => 1, 'url' => $url, 'redirect_url' => $productCategoryUrl, 'shop_id' => $model->shop_id));
269
        }
270
271
        return $model;
272
    }
273
274
    public function updateImageById(array $attributes, $productId, $imageId)
0 ignored issues
show
Unused Code introduced by
The parameter $productId is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

274
    public function updateImageById(array $attributes, /** @scrutinizer ignore-unused */ $productId, $imageId)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
275
    {
276
        $attributes['modified_by_user_id'] = auth('hideyobackend')->user()->id;
0 ignored issues
show
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
277
        $image = $this->findImage($imageId);
278
279
        if (count($attributes) > 0) {
280
            $image->fill($attributes);
281
            
282
            $image->relatedProductAttributes()->sync(array());
283
            if (isset($attributes['productAttributes'])) {
284
                $image->relatedProductAttributes()->sync($attributes['productAttributes']);
285
            }
286
            
287
            $image->relatedAttributes()->sync(array());
288
            if (isset($attributes['attributes'])) {
289
                $image->relatedAttributes()->sync($attributes['attributes']);
290
            }
291
292
            $image->save();
293
        }
294
295
        return $image;
296
    }
297
298
    public function destroy($productId)
299
    {
300
        $model = $this->find($productId);
301
302
        if ($model->productCategory) {
303
            $url = $model->shop->url.route('product.item', ['productId' => $model->id, 'productSlug' => $model->slug, 'categorySlug' => $model->productCategory->slug], null);
304
            $productCategoryUrl = $model->shop->url.route('product-category', ['slug' => $model->productCategory->slug], null);
305
            $this->redirect->create(array('active' => 1, 'url' => $url, 'redirect_url' => $productCategoryUrl, 'shop_id' => $model->shop_id));
0 ignored issues
show
Bug Best Practice introduced by
The property redirect does not exist on Hideyo\Ecommerce\Framewo...\Product\ProductService. Did you maybe forget to declare it?
Loading history...
306
        }
307
308
309
        if ($model->productImages()->count()) {
310
            foreach ($model->productImages()->get() as $image) {
311
                $this->productImage->destroy($image->id);
0 ignored issues
show
Bug Best Practice introduced by
The property productImage does not exist on Hideyo\Ecommerce\Framewo...\Product\ProductService. Did you maybe forget to declare it?
Loading history...
312
            }
313
        }
314
315
316
        $directory = $this->storageImagePath.$model->id;
317
        File::deleteDirectory($directory);
318
319
        File::deleteDirectory($this->publicImagePath.$model->id);
320
        $model->addAllToIndex();
321
        return $model->delete();
322
    }
323
324
325
    public function destroyImage($imageId)
326
    {
327
        $modelImage = $this->findImage($imageId);
328
        $filename = $modelImage->path;
329
        $shopId = auth('hideyobackend')->user()->selected_shop_id;
0 ignored issues
show
Bug introduced by
Accessing selected_shop_id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
330
        $shop = ShopService::find($shopId);
331
        
332
        if (File::exists($filename)) {
333
            File::delete($filename);
334
335
336
            if ($shop->thumbnail_square_sizes) {
337
                $sizes = explode(',', $shop->thumbnail_square_sizes);
338
                if ($sizes) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $sizes of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
339
                    foreach ($sizes as $valueSize) {
340
                        File::delete($this->publicImagePath.$valueSize."/".$modelImage->product_id."/".$modelImage->file);
341
                    }
342
                }
343
            }
344
        }
345
346
        return $modelImage->delete();
347
    }
348
349
350
    public function priceDetails($product, $field)
351
    {
352
        $preSaleDiscount = session()->get('preSaleDiscount');
353
354
        if ($product->price) {
355
356
            $taxRate = 0;
357
            $priceInc = 0;
358
            $taxValue = 0;
359
360
            if (isset($product->taxRate)) {
361
                $taxRate = $product->taxRate->rate;        
362
                $priceInc = (($product->taxRate->rate / 100) * $product->price) + $product->price;
363
                $taxValue = $priceInc - $product->price;
364
            }
365
366
            $discountPriceInc = $priceInc;
367
            $discountPriceEx = $product->price;
368
            $discountTaxRate = 0;
369
370
            if($preSaleDiscount) {
371
372
                if ($preSaleDiscount['value'] AND $preSaleDiscount['collection_id'] == $product->collection_id) {
373
374
                    if ($preSaleDiscount['discount_way'] == 'amount') {
375
                        $discountPriceInc = $priceInc - $product->value;
376
                        $discountPriceEx = $discountPriceInc / 1.21;
377
                    } elseif ($preSaleDiscount['discount_way'] == 'percent') {
378
          
379
                        $tax = ($preSaleDiscount['value'] / 100) * $priceInc;
380
                        $discountPriceInc = $priceInc - $tax;
381
                        $discountPriceEx = $discountPriceInc / 1.21;                       
382
                    }
383
                    $discountTaxRate = $discountPriceInc - $discountPriceEx;                   
384
                }
385
386
                if($preSaleDiscount['products']) {
387
388
                    $productIds = array_column($preSaleDiscount['products'], 'id');
389
390
                    if (in_array($product->id, $productIds) OR (isset($product->product_id) AND in_array($product->product_id, $productIds))) {
391
392
                        if ($preSaleDiscount['discount_way'] == 'amount') {
393
                            $discountPriceInc = $priceInc - $product->value;
394
                            $discountPriceEx = $discountPriceInc / 1.21;
395
                        } elseif ($preSaleDiscount['discount_way'] == 'percent') {
396
              
397
                            $tax = ($preSaleDiscount['value'] / 100) * $priceInc;
398
                            $discountPriceInc = $priceInc - $tax;
399
                            $discountPriceEx = $discountPriceInc / 1.21;                       
400
                        }
401
                        $discountTaxRate = $discountPriceInc - $discountPriceEx;
402
                    }
403
404
                }
405
            } else {
406
                if ($product->discount_value) {
407
                    if ($product->discount_type == 'amount') {
408
409
                        $discountPriceInc = $priceInc - $product->discount_value;
410
                        $discountPriceEx = $discountPriceInc / 1.21;
411
                    } elseif ($product->discount_type == 'percent') {
412
413
                        $tax = ($product->discount_value / 100) * $priceInc;
414
                        $discountPriceInc = $priceInc - $tax;
415
                        $discountPriceEx = $discountPriceInc / 1.21;
416
                    }
417
                    $discountTaxRate = $discountPriceInc - $discountPriceEx;
418
                }
419
            }
420
421
            $productArray = array(
422
                'original_price_ex_tax'  => $product->price,
423
                'original_price_ex_tax_number_format'  => number_format($product->price, 2, '.', ''),
424
                'original_price_inc_tax' => $priceInc,
425
                'original_price_inc_tax_number_format' => number_format($priceInc, 2, '.', ''),
426
                'tax_rate' => $taxRate,
427
                'tax_value' => $taxValue,
428
                'currency' => 'EU',
429
                'discount_price_inc' => $discountPriceInc,
430
                'discount_price_inc_number_format' => number_format($discountPriceInc, 2, '.', ''),
431
                'discount_price_ex' => $discountPriceEx,
432
                'discount_price_ex_number_format' => number_format($discountPriceEx, 2, '.', ''),
433
                'discount_tax_value' => $discountTaxRate,
434
                'discount_value' => $product->discount_value,
435
                'amount' => $product->amount
436
            );
437
        
438
            if (isset($productArray[$field])) {
439
                return $productArray[$field];
440
            }         
441
        } 
442
443
        return false;
444
    }
445
446
    public function getImage($productId, $combinationsIds, $productAttributeId = false)
447
    {
448
        $product = $this->getModel();
449
        $product = $product->has('productImages')->where('id', '=', $productId)->first();
450
        $images = array();
0 ignored issues
show
Unused Code introduced by
The assignment to $images is dead and can be removed.
Loading history...
451
452
        if($product AND $product->productImages->count()) {  
453
454
            $images = $product->productImages()->has('relatedAttributes', '=', 0)->has('relatedProductAttributes', '=', 0)->orderBy('rank', '=', 'asc')->get();
455
456
            if($combinationsIds) {
457
458
                $imagesRelatedAttributes = $this->getImageModel()->
459
                whereHas('relatedAttributes', function($query) use ($combinationsIds, $product, $productId) { $query->with(array('productImage'))->whereIn('attribute_id', $combinationsIds); });
0 ignored issues
show
Unused Code introduced by
The import $productId is not used and could be removed.

This check looks for imports that have been defined, but are not used in the scope.

Loading history...
Unused Code introduced by
The import $product is not used and could be removed.

This check looks for imports that have been defined, but are not used in the scope.

Loading history...
460
                
461
                $images = $images->merge($imagesRelatedAttributes)->sortBy('rank');          
462
            }
463
464
            if($productAttributeId) {                
465
                $imagesRelatedProductAttributes = $this->getImageModel()->
466
                whereHas('relatedProductAttributes', function($query) use ($productAttributeId, $product) { $query->where('product_attribute_id', '=', $productAttributeId); })
0 ignored issues
show
Unused Code introduced by
The import $product is not used and could be removed.

This check looks for imports that have been defined, but are not used in the scope.

Loading history...
467
                ->where('product_id', '=', $productId)
468
                ->get();
469
470
                $images = $images->merge($imagesRelatedProductAttributes)->sortBy('rank');
471
            }
472
473
474
            if(!$images->count()) {
475
                $images = $product->productImages()->orderBy('rank', '=', 'asc')->get();
476
            }
477
478
            if ($images->count()) {
479
                return $images->first()->file;
480
            }
481
        }
482
    }
483
484
485
  public function increaseAmounts($products)
486
    {
487
        if ($products->count()) {
488
            foreach ($products as $product) {
489
                if ($product->product_id) {
490
                    $model = $this->find($product->product_id);
491
                    if ($model) {
492
                        $attributes = array(
493
                            'title' => $model->title,
494
                            'amount' => $model->amount + $product->amount
495
                        );
496
                    }
497
                }
498
499
                $model->fill($attributes);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $attributes does not seem to be defined for all execution paths leading up to this point.
Loading history...
Comprehensibility Best Practice introduced by
The variable $model does not seem to be defined for all execution paths leading up to this point.
Loading history...
500
501
    
502
503
                $model->save();
504
            }
505
        }
506
    }
507
508
    public function reduceAmounts($products)
509
    {
510
        if ($products->count()) {
511
            foreach ($products as $product) {
512
                if ($product->product_id) {
513
                    $model = $this->find($product->product_id);
514
                    if ($model) {
515
                        $attributes = array(
516
                            'title' => $model->title,
517
                            'amount' => $model->amount - $product->amount
518
                        );
519
                    }
520
                }
521
522
                $model->fill($attributes);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $model does not seem to be defined for all execution paths leading up to this point.
Loading history...
Comprehensibility Best Practice introduced by
The variable $attributes does not seem to be defined for all execution paths leading up to this point.
Loading history...
523
                $model->save();
524
            }
525
        }
526
    }
527
528
    public function changeActive($productId)
529
    {
530
        $model = $this->find($productId);
531
532
        if ($model) {
533
534
            $active = 1;
535
            
536
            if ($model->active) {
537
                $active = 0;
538
            }
539
540
            $attributes = array(
541
                'active' => $active
542
            );
543
544
            $model->fill($attributes);
545
546
            // if (!$model->active) {
547
            //     $url = $model->shop->url.route('product.item', ['productId' => $model->id, 'productSlug' => $model->slug, 'categorySlug' => $model->productCategory->slug], null);
548
            //     $productCategoryUrl = $model->shop->url.route('product-category', ['slug' => $model->productCategory->slug], null);
549
            //     $redirectResult = $this->redirect->create(array('active' => 1, 'url' => $url, 'redirect_url' => $productCategoryUrl, 'shop_id' => $model->shop_id));
550
            // } else {
551
            //     $url = $model->shop->url.route('product.item', ['productId' => $model->id, 'productSlug' => $model->slug, 'categorySlug' => $model->productCategory->slug], null);
552
            //     $this->redirect->destroyByUrl($url);
553
            // }
554
555
            return $model->save();
556
        }
557
558
        return false;
559
    }
560
561
    public function changeAmount($productId, $amount)
562
    {
563
        $model = $this->find($productId);
564
565
        if ($model) {
566
            $attributes = array(
567
                'amount' => $amount
568
            );
569
570
            $model->fill($attributes);
571
            return $model->save();
572
        }
573
574
        return false;
575
    }
576
577
    public function changeRank($productId, $rank)
578
    {
579
        $model = $this->find($productId);
580
581
        if ($model) {
582
            $attributes = array(
583
                'rank' => $rank
584
            );
585
586
            $model->fill($attributes);
587
588
            return $model->save();
589
        }
590
591
        return false;
592
    }
593
594
595
    public function selectOneById($productId)
596
    {
597
        return $this->repo->selectOneById($productId);
598
    }
599
600
    public function selectOneByShopIdAndId($shopId, $productId, $attributeId = false)
601
    {
602
       return $this->repo->selectOneByShopIdAndId($shopId, $productId, $attributeId);
603
    }
604
605
    public function ajaxProductImages($product, $combinationsIds, $productAttributeId = false) 
606
    {
607
        return $this->repo->ajaxProductImages($product, $combinationsIds, $productAttributeId);
608
    }
609
610
    public  function selectAllByShopIdAndProductCategoryId($shopId, $productCategoryId, $filters = false)
611
    {
612
        return $this->repo->selectAllByShopIdAndProductCategoryId($shopId, $productCategoryId, $filters);
613
    }
614
615
    public function findImage($imageId)
616
    {
617
        return $this->repo->findImage($imageId);
618
    }
619
620
    public function getImageModel()
621
    {
622
        return $this->repo->getImageModel();
623
    }
624
625
626
}