ProductsController   C
last analyzed

Complexity

Total Complexity 72

Size/Duplication

Total Lines 475
Duplicated Lines 9.89 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 0
Metric Value
wmc 72
lcom 1
cbo 11
dl 47
loc 475
rs 5.5667
c 0
b 0
f 0

27 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 23 23 1
B save() 0 24 4
A show() 0 21 2
A getSalledPercent() 0 8 2
A getSpecifications() 0 7 1
A getSpecificationsColor() 0 7 1
A remove() 0 18 3
A saveSpecifications() 0 8 3
D saveSpecificationsPrice() 0 39 20
A saveImprovedSpecifications() 0 8 2
A removeSpec() 0 12 2
A removeSpecPrice() 0 5 1
A removeImproveSpec() 0 6 1
A addImage() 0 10 2
A removeImage() 0 4 1
A saveImagesOrder() 0 23 1
A getChangedSortPositions() 0 13 2
A setNewRankToChangedPositions() 0 9 1
A loadSpecPrice() 0 7 2
A loadSpecPriceDescription() 0 6 3
A loadImprovedSpecPrice() 0 6 3
A loadSpecPriceColor() 0 7 4
A loadSpec() 0 5 2
A removeGroupPrice() 0 9 2
A removeSpecPriceDescription() 8 8 2
A removeGroupSizeColor() 8 8 2
A removeSpecPriceColor() 8 8 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like ProductsController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ProductsController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace App\Http\Controllers;
4
5
use App\Http\Requests\ProductCreateRequest;
6
use App\Http\Requests\ProductUpdateRequest;
7
use App\Http\Requests\SaveProductRequest;
8
use App\Image;
9
use App\ImprovedSpec;
10
use App\Lot;
11
use App\Repositories\ImprovedSpecRepository;
12
use App\Repositories\SpecPriceRepository;
13
use App\Repositories\LotRepository;
14
use Illuminate\Support\Facades\Auth;
15
use App\Product;
16
use App\Repositories\CategoryableRepository;
17
use App\Repositories\InvolvedRepository;
18
use App\Repositories\ModelColorsRepository;
19
use App\Services\ImageProcessor;
20
use Illuminate\Http\Request;
21
use Illuminate\Http\UploadedFile;
22
use Illuminate\Session\Store;
23
use App\Repositories\ProductsRepository;
24
use App\Repositories\CurrenciesRepository;
25
use XmlParser;
26
use Storage;
27
28
class ProductsController extends Controller
29
{
30
    /**
31
     * @var ProductsRepository
32
     */
33
    protected $products;
34
35
    /**
36
     * @var CategoryableRepository
37
     */
38
    protected $categoryable;
39
40
    /**
41
     * @var Store
42
     */
43
    protected $session;
44
45
    /**
46
     * @var InvolvedRepository
47
     */
48
    protected $involved;
49
50
    /**
51
     * @var modelColorsRepository
52
     */
53
    protected $modelColors;
54
55
    /**
56
     * @var LotRepository
57
     */
58
    protected $lots;
59
60
    /**
61
     * @var ImprovedSpec
62
     */
63
    protected $improvedSpecs;
64
    protected $specPrice;
65
    protected $currencies;
66
67
    /**
68
     * ProductsController constructor.
69
     * @param Store $session
70
     * @param ProductsRepository $productsRepository
71
     * @param CategoryableRepository $categoryableRepository
72
     * @param ModelColorsRepository $modelColorsRepository
73
     * @param InvolvedRepository $involvedRepository
74
     * @param LotRepository $lotRepository
75
     * @param ImprovedSpecRepository $improvedSpecRepository
76
     */
77 View Code Duplication
    public function __construct(
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
78
        Store $session,
79
        ProductsRepository $productsRepository,
80
        CategoryableRepository $categoryableRepository,
81
        ModelColorsRepository $modelColorsRepository,
82
        InvolvedRepository $involvedRepository,
83
        LotRepository $lotRepository,
84
        ImprovedSpecRepository $improvedSpecRepository,
85
        SpecPriceRepository $specPriceRepository,
86
        CurrenciesRepository $currenciesRepository
87
    )
88
    {
89
        $this->session       = $session;
90
        $this->products      = $productsRepository;
91
        $this->categoryable  = $categoryableRepository;
92
        $this->modelColors   = $modelColorsRepository;
0 ignored issues
show
Documentation Bug introduced by
It seems like $modelColorsRepository of type object<App\Repositories\ModelColorsRepository> is incompatible with the declared type object<App\Http\Controll...\modelColorsRepository> of property $modelColors.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
93
        $this->involved      = $involvedRepository;
94
        $this->lots          = $lotRepository;
95
        $this->improvedSpecs = $improvedSpecRepository;
0 ignored issues
show
Documentation Bug introduced by
It seems like $improvedSpecRepository of type object<App\Repositories\ImprovedSpecRepository> is incompatible with the declared type object<App\ImprovedSpec> of property $improvedSpecs.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
96
        $this->specPrice     = $specPriceRepository;
97
        $this->currencies    = $currenciesRepository;
98
99
    }
100
101
    /**
102
     * @param SaveProductRequest $request
103
     * @param Product $product
104
     * @return mixed
105
     */
106
    public function save(SaveProductRequest $request, Lot $lot, Product $product)
0 ignored issues
show
Unused Code introduced by
The parameter $lot is not used and could be removed.

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

Loading history...
107
    {
108
        $product = $this->products->saveProduct($product, $request->all());
109
110
        if (!empty($spec_price = $request->get('spec_price')))
111
            $this->saveSpecificationsPrice($request,$product);
112
113
        if (!empty($spec = $request->get('spec')))
114
            $this->saveSpecifications($spec, $product);
115
116
        if (!empty($fileInput = $request->file('image')))
117
            array_walk($fileInput, function($image) use (&$product){
118
                $this->addImage($image, $product);
119
            });
120
121
       /* if (!empty($specs = $request->get('i_spec')))
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
122
            $this->saveImprovedSpecifications($specs, $product);*/
123
124
        $json = array(
125
            'respons' => true
126
        );
127
        return response($json);
0 ignored issues
show
Documentation introduced by
$json is of type array<string,boolean,{"respons":"boolean"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
128
        //return view('lots.partials.form.product', [ 'lot' => $lot, 'product' => $product]);
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
129
    }
130
131
    /**
132
     * Show inner product.
133
     *
134
     * @param $product
135
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
136
     */
137
    public function show($product)
138
    {
139
        $itemPercentage = $this->getSalledPercent($product->id);
140
        $lot            = $this->lots->find($product->lot_id);
141
        $productInLot   = $this->products->countInLotProduct($product->lot_id);
142
        $same_products  = $this->products->getSameProduct($product->sub_category_id);
143
        $view = view('product.show',['item'=>$product,'lot'=>$lot,'similar'=>$same_products ,'productItem'=> $itemPercentage,'productinlot'=>$productInLot]);
144
145
        if(Auth::check()) {
146
            $auth_is_involved = $this->involved
147
                ->checkIfAuthInvolved($product);
148
149
            return $view
150
                ->withUserIsInvolved($auth_is_involved)
151
                ->withInvolved($this->involved->getModelByUserAndProduct($product));
152
        }
153
154
        return $view
155
            ->withUserIsInvolved(false)
156
            ->withSame($same_products);
157
    }
158
159
/*    public function convertAmount(){
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
160
        $xml = XmlParser::load('http://www.bnm.org/ro/official_exchange_rates?get_xml=1&date='.date("d.m.Y"));
161
162
        $parsed = $xml->parse([
163
            'cursToDay' => ['uses' => 'Valute[CharCode,Value]'],
164
        ]);
165
166
        $currency = array('EUR','USD');
167
        $json = array();
168
        foreach ($parsed as $key => $item) {
169
            foreach ($item as $key => $val) {
170
                if (in_array($val['CharCode'], $currency)) {
171
                    $json[$val['CharCode']] = $val['Value'];
172
                }
173
            }
174
        }
175
        $put = Storage::put('json_currency.json', json_encode($json));
176
    }*/
177
178
    public function getSalledPercent($id)
179
    {
180
        $count = $this->products->getCount($id);
181
        $selled = $this->involved->getCountSelled($id);
182
        ($count) ? $result = number_format((100 * $selled)  / $count) : $result = 0;
183
184
        return array(['totalItems'=>$count,'salePercent'=>$result]);
185
    }
186
187
188
    public function getSpecifications() {
189
190
        $request =  \Request::all();
191
        $getSpecification = $this->improvedSpecs->getById($request['id']);
0 ignored issues
show
Documentation Bug introduced by
The method getById does not exist on object<App\ImprovedSpec>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
192
193
        return json_encode($getSpecification);
194
    }
195
196
    public function getSpecificationsColor() {
197
198
        $request =  \Request::all();
199
        $getSpecificationColor = $this->modelColors->getById($request['id']);
200
201
        return json_encode($getSpecificationColor);
202
    }
203
204
205
    /**
206
     * Delete products..
207
     *
208
     * @param Request $request
209
     * @param Lot $lot
210
     *
211
     * @return string
212
     */
213
    public function remove(Request $request, Lot $lot)
0 ignored issues
show
Unused Code introduced by
The parameter $lot is not used and could be removed.

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

Loading history...
214
    {
215
        $product    = $this->products->find($request->get('product_id'));
216
        if ($product) {
217
            foreach ($product->specPrice as $key => $price) {
0 ignored issues
show
Documentation introduced by
The property specPrice does not exist on object<App\Product>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
218
                $price->removeMetaGroupById('price', $price->id);
219
            }
220
            $product->removeMetaGroupById('spec', $request->get('product_id'));
221
        }
222
        $this->products->delete($request->get('product_id'));
223
224
        /*if($this->lots->checkIfPossibleToChangeCategory($lot))
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
225
            return 'enable_cat';*/
226
        $json = array(
227
            'respons' => true
228
        );
229
        return response($json);
0 ignored issues
show
Documentation introduced by
$json is of type array<string,boolean,{"respons":"boolean"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
230
    }
231
232
    /**
233
     * Save specifications.
234
     *
235
     * @param $specifications
236
     * @param $product
237
     */
238
    private function saveSpecifications($specifications, Product $product)
239
    {
240
        array_walk($specifications, function ($meta) use ($product) {
241
            if ($meta['key'] != null  && $meta['value'] != null) {
242
                $product->setMeta($meta, 'spec');
243
            }
244
        });
245
    }
246
247
248
    private function saveSpecificationsPrice($request, Product $product)
249
    {
250
        //dd($request->get('spec_price'));
0 ignored issues
show
Unused Code Comprehensibility introduced by
80% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
251
        //dd(collect($request->get('spec_price'))->first());
0 ignored issues
show
Unused Code Comprehensibility introduced by
77% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
252
        //$collection = $request->get('spec_price');
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
253
       /* $collection = collect($request->get('spec_price'));
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
254
        $filtered = $collection->filter(function ($item) {
255
            return $item['new_price'] != '' && $item['old_price'] != '';
256
        })->values();
257
        dd($filtered->all());*/
258
        if (!empty($spec = $request->get('spec_price'))) {
259
            foreach ($spec as $key => $price) {
260
                if (($price['new_price'] >= 0 && $price['old_price'] >= 0) && ($price['new_price'] != null && $price['old_price'] != null)) {
261
                    $specPriceInsert = $this->specPrice->save($price, $product);
262
                    if (!empty($specMeta = $price['spec_desc'])) {
263
                        foreach ($specMeta as $meta) {
264
                            if ($meta['key'] != null  && $meta['value'] != null) {
265
                                $specPriceInsert->setMeta($meta, 'price');
266
                            }
267
                        }
268
                    }
269
                    if (!empty($specSize = $price['size'])) {
270
                        foreach ($specSize as $key => $size) {
271
                            if ($size['size'] >= 0  && $size['size'] != null) {
272
                                $specSizeInsert = $this->improvedSpecs->save($size, $specPriceInsert);
0 ignored issues
show
Unused Code introduced by
The call to ImprovedSpec::save() has too many arguments starting with $specPriceInsert.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
273
                                if (!empty($specColor = $size['color'])) {
274
                                    foreach ($specColor as $key => $color) {
275
                                        if ($color['color_hash'] != null  or ($color['amount'] >= 0 && $color['amount'] != null)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
276
                                            $specColorInsert = $this->modelColors->save($color, $specSizeInsert);
0 ignored issues
show
Unused Code introduced by
$specColorInsert is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
277
                                        }
278
                                    }
279
                                }
280
                            }
281
                        }
282
                    }
283
                }
284
            }
285
        }
286
    }
287
288
    private function saveImprovedSpecifications($specs, $product)
0 ignored issues
show
Unused Code introduced by
The parameter $product is not used and could be removed.

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

Loading history...
289
    {
290
        array_walk($specs, function($data, $product){
0 ignored issues
show
Unused Code introduced by
The parameter $product is not used and could be removed.

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

Loading history...
291
            $spec = $this->improvedSpecs->find($spec_id);
0 ignored issues
show
Bug introduced by
The variable $spec_id does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Documentation Bug introduced by
The method find does not exist on object<App\ImprovedSpec>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
292
            if($spec)
293
                $this->improvedSpecs->update($spec, $data);
294
        });
295
    }
296
297
    /**
298
     * Remove spec.
299
     *
300
     * @param Request $request
301
     *
302
     * @return void
303
     */
304
    public function removeSpec(Request $request)
305
    {
306
        $product = $this->products->find($request->get('product_id'));
307
        if ($product) {
308
            $product->removeMetaByKey($request->get('key'));
309
        }
310
        $json = array(
311
            'respons' => true
312
        );
313
        return response($json);
0 ignored issues
show
Documentation introduced by
$json is of type array<string,boolean,{"respons":"boolean"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
314
        
315
    }
316
317
    public function removeSpecPrice(Request $request)
318
    {
319
        $spec = $this->specPrice->find($request->get('spec_id'));
320
        $this->specPrice->delete($spec);
321
    }
322
    /**
323
     * Remove improved spec.
324
     *
325
     * @param Request $request
326
     * @param Lot $lot
327
     *
328
     * @return void
329
     */
330
    public function removeImproveSpec(Request $request, Lot $lot)
0 ignored issues
show
Unused Code introduced by
The parameter $lot is not used and could be removed.

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

Loading history...
331
    {
332
        $spec = $this->improvedSpecs->find($request->get('spec_id'));
0 ignored issues
show
Documentation Bug introduced by
The method find does not exist on object<App\ImprovedSpec>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
333
334
        $this->improvedSpecs->delete($spec);
0 ignored issues
show
Unused Code introduced by
The call to ImprovedSpec::delete() has too many arguments starting with $spec.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
335
    }
336
337
    /**
338
     * Add image to product.
339
     *
340
     * @param $image
341
     * @param Product $product
342
     *
343
     * @return mixed
344
     */
345
    public function addImage($image, Product $product)
346
    {
347
        if ($image instanceof UploadedFile) {
348
            $location = 'upload/products/' . $product->id;
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<App\Product>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
349
            $processor = new ImageProcessor();
350
            $imageable = $processor->uploadAndCreate($image, $product, null, $location);
351
352
            return $imageable;
353
        }
354
    }
355
356
    /**
357
     * Remove Image.
358
     *
359
     * @param Request $request
360
     * @param $lot
361
     */
362
    public function removeImage(Request $request, $lot)
0 ignored issues
show
Unused Code introduced by
The parameter $lot is not used and could be removed.

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

Loading history...
363
    {
364
        Image::find($request->get('image_id'))->delete();
365
    }
366
367
    /**
368
     * Save image order.
369
     *
370
     * @param Request $request
371
     * @param $product
372
     */
373
    public function saveImagesOrder(Request $request, $product)
374
    {
375
        $sorted = $request->get('item');
376
377
        $newsort = [];
378
        array_walk($sorted, function ($id, $k) use (&$newsort){
379
            $image = Image::find($id);
380
381
            $newsort[$k] = ['id' => $image->id, 'rank' => $image->rank];
382
        });
383
384
        $oldsort = [];
385
        $product->images()->ranked('asc')->get()->each(function ($item, $k) use(&$oldsort)
386
        {
387
            $oldsort[$k] = ['id' => $item->id, 'rank' => $item->rank];
388
        });
389
390
        $this->setNewRankToChangedPositions(
391
            $this->getChangedSortPositions($newsort, $oldsort),
392
            $newsort,
393
            $oldsort
394
        );
395
    }
396
397
    /**
398
     * Get only changed positions of sorted elements.
399
     *
400
     * @param $newsort
401
     * @param $oldsort
402
     * @return array
403
     */
404
    private function getChangedSortPositions($newsort, $oldsort)
405
    {
406
        $temp = [];
407
        array_walk($newsort, function ($sorted_attribs, $position) use ($oldsort, $newsort, &$temp)
408
        {
409
            if($oldsort[$position]['id'] !== $newsort[$position]['id'])
410
            {
411
                $temp[] = $position;
412
            }
413
        });
414
415
        return $temp;
416
    }
417
418
    /**
419
     * Save sorted ranks to changed positions.
420
     *
421
     * @param $changed_positions
422
     * @param $newsort
423
     * @param $oldsort
424
     */
425
    private function setNewRankToChangedPositions($changed_positions, $newsort, $oldsort)
426
    {
427
        array_walk($changed_positions, function ($position) use ($oldsort, $newsort)
428
        {
429
            $image = Image::find($newsort[$position]['id']);
430
431
            $image->setRank($oldsort[$position]['rank']);
432
        });
433
    }
434
435
436
437
    public function loadSpecPrice(Request $request, Lot $lot)
438
    {
439
        $key_spec   = ($request->has('key_spec')) ? $request->get('key_spec') : 1;
440
        $product    = $this->products->find($request->get('product_id'));
441
        $currencies = $this->currencies->getPublic();
442
        return view('lots.partials.form.specification_price', ['currencies' => $currencies,'lot' => $lot,'product' => $product,'key_spec' => $key_spec]);
443
    }
444
    public function loadSpecPriceDescription(Request $request)
445
    {
446
        $key_desc = ($request->has('key_desc')) ? $request->get('key_desc') : 1;
447
        $key_spec = ($request->has('key_spec')) ? $request->get('key_spec') : 1;
448
        return view('lots.partials.form.description_specs', ['key_spec' => $key_spec,'key_desc' => $key_desc]);
449
    }
450
    public function loadImprovedSpecPrice(Request $request)
451
    {
452
        $key_spec = ($request->has('key_spec')) ? $request->get('key_spec') : 1;
453
        $key_size = ($request->has('key_size')) ? $request->get('key_size') : 1;
454
        return view('lots.partials.form.size_specs', ['key_spec' => $key_spec,'key_size' => $key_size]);
455
    }
456
    public function loadSpecPriceColor(Request $request)
457
    {
458
        $key_spec  = ($request->has('key_spec')) ? $request->get('key_spec') : 1;
459
        $key_size  = ($request->has('key_size')) ? $request->get('key_size') : 1;
460
        $key_color = ($request->has('key_color')) ? $request->get('key_color') : 1;
461
        return view('lots.partials.form.color_specs', ['key_spec' => $key_spec,'key_size' => $key_size,'key_color' => $key_color]);
462
    }
463
    public function loadSpec(Request $request)
464
    {
465
        $key_spec_product  = ($request->has('key_spec_product')) ? $request->get('key_spec_product') : 1;
466
        return view('lots.partials.form.specification', ['key_spec_product' => $key_spec_product]);
467
    }
468
469
    public function removeGroupPrice(Request $request)
470
    {
471
        $spec = $this->specPrice->findKey($request->get('key'));
472
        if ($spec) {
473
            $spec->removeMetaGroupById('price', $spec->id);
474
            $this->specPrice->delete($spec->id);
475
        }
476
        return response(array('type' => true));
0 ignored issues
show
Documentation introduced by
array('type' => true) is of type array<string,boolean,{"type":"boolean"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
477
    }   
478 View Code Duplication
    public function removeSpecPriceDescription(Request $request)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
479
    {
480
        $spec = $this->specPrice->findKey($request->get('key_price'));
481
        if ($spec) {
482
            $spec->removeMetaByKey($request->get('key'));
483
        }
484
        return response(array('type' => true));
0 ignored issues
show
Documentation introduced by
array('type' => true) is of type array<string,boolean,{"type":"boolean"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
485
    }
486 View Code Duplication
    public function removeGroupSizeColor(Request $request)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
487
    {
488
        $spec = $this->improvedSpecs->findKey($request->get('key'));
0 ignored issues
show
Documentation Bug introduced by
The method findKey does not exist on object<App\ImprovedSpec>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
489
        if ($spec) {
490
            $this->improvedSpecs->delete($spec);
0 ignored issues
show
Unused Code introduced by
The call to ImprovedSpec::delete() has too many arguments starting with $spec.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
491
        }
492
        return response(array('type' => true));
0 ignored issues
show
Documentation introduced by
array('type' => true) is of type array<string,boolean,{"type":"boolean"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
493
    }
494 View Code Duplication
    public function removeSpecPriceColor(Request $request)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
495
    {
496
        $spec = $this->modelColors->findKey($request->get('key'));
497
        if ($spec) {
498
            $this->modelColors->delete($spec);
499
        }
500
        return response(array('type' => true));
0 ignored issues
show
Documentation introduced by
array('type' => true) is of type array<string,boolean,{"type":"boolean"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
501
    }
502
}