GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Push — packet_price_editor ( 6e890b...12d4e8 )
by
unknown
10:05
created

BatchEditPriceAction::checkAndRound()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 15
rs 9.4285
cc 3
eloc 9
nc 3
nop 1
1
<?php
2
namespace app\modules\shop\actions;
3
4
use Yii;
5
use yii\base\Action;
6
use yii\web\Response;
7
use yii\web\NotFoundHttpException;
8
use app\modules\shop\models\Category;
9
use app\modules\shop\models\Product;
10
11
class BatchEditPriceAction extends Action
12
{
13
    const BEP_CONTEXT_PRODUCT = 'backend-product';
14
    const BEP_KIND_FIXED = 'fixed';
15
    const BEP_KIND_PERCENT = 'percentage';
16
    const BEP_TYPE_NORMAL = 'normal';
17
    const BEP_TYPE_RELATIVE = 'relative';
18
    const BEP_FIELD_PRICE = 'price';
19
    const BEP_FIELD_OLDPRICE = 'old_price';
20
    const BEP_FIELD_ALL = 'all';
21
    const BEP_INCREMENT = 'inc';
22
    const BEP_DECREMENT = 'dec';
23
24
    public $params = [];
25
    
26
    public function run()
27
    {
28
        if (false === Yii::$app->request->isAjax) {
29
            throw new NotFoundHttpException();
30
        }
31
        Yii::$app->response->format = Response::FORMAT_JSON;
32
33
        $this->params = [
34
            'is_child_inc' => Yii::$app->request->post('is_child_inc', false),
35
            'kind' => Yii::$app->request->post('kind', ''),
36
            'operation' => Yii::$app->request->post('operation', ''),
37
            'is_round' => Yii::$app->request->post('is_round', true),
38
            'round_val' => intval(Yii::$app->request->post('round_val', 2)),
39
            'sel_field' => Yii::$app->request->post('apply_for', ''),
40
            'value' => floatval(Yii::$app->request->post('value', 0)),
41
            'type' => Yii::$app->request->post('type', ''),
42
            'currency_id' => intval(Yii::$app->request->post('currency_id', 0)),
43
            'context' => Yii::$app->request->post('context', ''),
44
            'items' => Yii::$app->request->post('items', [])
45
        ];
46
47
        return $this->editPrices();
48
    }
49
50
    /**
51
     * Get list of child categories
52
     * @param $list int[]
53
     * @return int[]
54
     */
55
    protected function getParentCategories($list)
56
    {
57
        if ($this->params['is_child_inc']) {
58
            $count = count($list);
59
            for ($i = 0; $i < $count; $i++) {
60
                $cats = Category::getByParentId($list[$i]);
61
                foreach ($cats as $category) {
62
                    $list[] = $category->id;
63
                    $count ++;
64
                }
65
            }
66
        }
67
        
68
        return $list;
69
    }
70
71
    /**
72
     * Get parameters to build queries
73
     * @return mixed[]
0 ignored issues
show
Documentation introduced by
Should the return type not be array<string,array<*,\yi...on>|\yii\db\Expression>?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
74
     */
75
    protected function getSqlStatements()
76
    {
77
        $updateRule = [];
78
        $condition = [];
79
        $args = [];
80
81
        $conditionFormat = '%s %s >= 0';
0 ignored issues
show
Unused Code introduced by
$conditionFormat 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...
82
        if ($this->params['is_round']) {
83
            $updateFormat = 'ROUND(%s %s, :round)';
84
        } else {
85
            $updateFormat = '%s %s';
86
        }
87
88
        // operation
89
        if ($this->params['operation'] == self::BEP_INCREMENT) {
90
            $operation = '+';
91
        } elseif ($this->params['operation'] == self::BEP_DECREMENT) {
92
            $operation = '-';
93
        }
94
        if ($this->params['kind'] == self::BEP_KIND_FIXED) {
95
            $args['operation'] = $operation . ' :val';
0 ignored issues
show
Bug introduced by
The variable $operation does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
96
        } elseif ($this->params['kind'] == self::BEP_KIND_PERCENT) {
97
            $args['operation'] = " * (1 {$operation} :val / 100)";
98
        }
99
100
        // price | old_price | both of them
101
        if ($this->params['type'] == self::BEP_TYPE_NORMAL) {
102 View Code Duplication
            if ($this->params['sel_field'] == self::BEP_FIELD_PRICE
103
                || $this->params['sel_field'] == self::BEP_FIELD_ALL
104
            ) {
105
                $args['field_to'] = self::BEP_FIELD_PRICE;
106
                $args['field_from'] = self::BEP_FIELD_PRICE;
107
            }
108 View Code Duplication
            if ($this->params['sel_field'] == self::BEP_FIELD_OLDPRICE) {
109
                $args['field_to'] = self::BEP_FIELD_OLDPRICE;
110
                $args['field_from'] = self::BEP_FIELD_OLDPRICE;
111
            }
112
113
            if ($this->params['sel_field'] == self::BEP_FIELD_ALL) {
114
                $updateRule[$args['field_to']] = new \yii\db\Expression(
115
                    sprintf(
116
                        $updateFormat,
117
                        $args['field_from'],
118
                        $args['operation']
119
                    )
120
                );
121
122
                $condition[] = $args['field_from'] . ' ' . $args['operation'] . '>= 0';
123
                $args['field_to'] = self::BEP_FIELD_OLDPRICE;
124
                $args['field_from'] = self::BEP_FIELD_OLDPRICE;
125
            }
126
        } elseif ($this->params['type'] == self::BEP_TYPE_RELATIVE) {
127 View Code Duplication
            if ($this->params['sel_field'] == self::BEP_FIELD_PRICE) {
128
                $args['field_to'] = self::BEP_FIELD_OLDPRICE;
129
                $args['field_from'] = self::BEP_FIELD_PRICE;
130
            }
131 View Code Duplication
            if ($this->params['sel_field'] == self::BEP_FIELD_OLDPRICE) {
132
                $args['field_to'] = self::BEP_FIELD_PRICE;
133
                $args['field_from'] = self::BEP_FIELD_OLDPRICE;
134
            }
135
        }
136
137
        $updateRule[$args['field_to']] = new \yii\db\Expression(
138
            sprintf(
139
                $updateFormat,
140
                $args['field_from'],
141
                $args['operation']
142
            )
143
        );
144
145
        $condition[] = $args['field_from'] . ' ' . $args['operation'] . ' >= 0';
146
        $condition[] = 'currency_id = :currency';
147
        if ($this->params['context'] == self::BEP_CONTEXT_PRODUCT) {
148
            $data = implode(',', $this->params['items']);
149
            $condition['for_count'] = 'id IN (' . $data . ')';
150
        } else {
151
            $data = implode(',', $this->getParentCategories($this->params['items']));
152
            $condition['for_count'] = 'main_category_id IN (' . $data . ')';
153
        }
154
155
        return [
156
            'rule' => $updateRule,
157
            'condition' => new \yii\db\Expression(implode(' AND ', $condition)),
158
            'condition_for_count' => new \yii\db\Expression($condition['for_count'])
159
        ];
160
    }
161
162
    /**
163
     * Editing of prices
164
     * @return int[]
165
     */
166
    protected function editPrices()
167
    {
168
        $sqlStatements = $this->getSqlStatements();
169
170
        $result['all'] = Product::find()
0 ignored issues
show
Coding Style Comprehensibility introduced by
$result was never initialized. Although not strictly required by PHP, it is generally a good practice to add $result = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
171
            ->where($sqlStatements['condition_for_count'])
172
            ->count();
173
174
        $result['success'] = Product::updateAll(
175
            $sqlStatements['rule'],
176
            $sqlStatements['condition'],
177
            [
178
                ':val' => $this->params['value'],
179
                ':round' => $this->params['round_val'],
180
                ':currency' => $this->params['currency_id']
181
            ]
182
        );
183
184
        return $result;
185
    }
186
}
187