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 — master ( b9b347...45f141 )
by Ivan
24s
created

PropertyStaticValues::attributeLabels()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 14
rs 9.4285
cc 1
eloc 11
nc 1
nop 0
1
<?php
2
3
namespace app\models;
4
5
use app\modules\shop\models\Product;
6
use app\properties\HasProperties;
7
use app\traits\GetImages;
8
use app\traits\SortModels;
9
use devgroup\TagDependencyHelper\ActiveRecordHelper;
10
use Yii;
11
use yii\behaviors\AttributeBehavior;
12
use yii\caching\TagDependency;
13
use yii\data\ActiveDataProvider;
14
use yii\db\ActiveQuery;
15
use yii\db\ActiveRecord;
16
use yii\db\Expression;
17
use app\modules\shop\models\Currency;
18
19
/**
20
 * This is the model class for table "property_static_values".
21
 * @property integer $id
22
 * @property integer $property_id
23
 * @property string $name
24
 * @property string $value
25
 * @property string $slug
26
 * @property integer $sort_order
27
 * @property Property $property
28
 * @property integer $dont_filter
29
 */
30
class PropertyStaticValues extends ActiveRecord
31
{
32
    use GetImages;
33
34
    public static $identity_map_by_property_id = [];
35
    private static $identity_map = [];
36
37
    use SortModels;
38
39
    /**
40
     * @inheritdoc
41
     */
42
    public function behaviors()
43
    {
44
        return [
45
            [
46
                'class' => AttributeBehavior::className(),
47
                'attributes' => [
48
                    \yii\db\ActiveRecord::EVENT_BEFORE_INSERT => 'sort_order',
49
                ],
50
                'value' => 0,
51
            ],
52
            [
53
                'class' => ActiveRecordHelper::className(),
54
            ],
55
            [
56
                'class' => HasProperties::className(),
57
            ],
58
        ];
59
    }
60
61
    /**
62
     * @inheritdoc
63
     */
64
    public static function tableName()
65
    {
66
        return '{{%property_static_values}}';
67
    }
68
69
    /**
70
     * @inheritdoc
71
     */
72 View Code Duplication
    public function rules()
73
    {
74
        return [
75
            [['property_id', 'name', 'value'], 'required'],
76
            [['property_id', 'sort_order', 'dont_filter'], 'integer'],
77
            [['title_prepend'], 'boolean'],
78
            [['name', 'value', 'slug', 'title_append'], 'string']
79
        ];
80
    }
81
82
    /**
83
     * @inheritdoc
84
     */
85
    public function attributeLabels()
86
    {
87
        return [
88
            'id' => Yii::t('app', 'ID'),
89
            'property_id' => Yii::t('app', 'Property ID'),
90
            'name' => Yii::t('app', 'Name'),
91
            'value' => Yii::t('app', 'Value'),
92
            'slug' => Yii::t('app', 'Slug'),
93
            'sort_order' => Yii::t('app', 'Sort Order'),
94
            'title_append' => Yii::t('app', 'Title append'),
95
            'title_prepend' => Yii::t('app', 'Prepend title?'),
96
            'dont_filter' => Yii::t('app', 'Don\'t filter (for FilterWidget only)'),
97
        ];
98
    }
99
100
    /**
101
     * Search tasks
102
     * @param $params
103
     * @return ActiveDataProvider
104
     */
105 View Code Duplication
    public function search($params)
106
    {
107
        $query = static::find()->where(['property_id' => $this->property_id]);
108
        $dataProvider = new ActiveDataProvider(
109
            [
110
                'query' => $query,
111
                'pagination' => [
112
                    'pageSize' => 10,
113
                ],
114
            ]
115
        );
116
        if (!($this->load($params))) {
117
            return $dataProvider;
118
        }
119
        $query->andFilterWhere(['id' => $this->id]);
120
        $query->andFilterWhere(['like', 'name', $this->name]);
121
        $query->andFilterWhere(['like', 'value', $this->value]);
122
        $query->andFilterWhere(['like', 'slug', $this->slug]);
123
        return $dataProvider;
124
    }
125
126
    public function getProperty()
127
    {
128
        return $this->hasOne(Property::className(), ['id' => 'property_id']);
129
    }
130
131
    /**
132
     * Возвращает Массив! по ID с использованием IdentityMap
133
     * @param int $id
134
     * @return null|PropertyStaticValues
135
     */
136 View Code Duplication
    public static function findById($id)
137
    {
138
        if (!isset(static::$identity_map[$id])) {
139
            $cacheKey = "PropertyStaticValue:$id";
140
141
            if (false === $property = Yii::$app->cache->get($cacheKey)) {
142
                if (null !== $property = static::find()->where(['id' => $id])->asArray()->one()) {
143
                    Yii::$app->cache->set(
144
                        $cacheKey,
145
                        $property,
146
                        0,
147
                        new TagDependency(
148
                            [
149
                                'tags' => [
150
                                    \devgroup\TagDependencyHelper\ActiveRecordHelper::getObjectTag(
151
                                        static::className(),
152
                                        $id
153
                                    ),
154
                                ],
155
                            ]
156
                        )
157
                    );
158
                }
159
            }
160
            static::$identity_map[$id] = $property;
161
        }
162
        return static::$identity_map[$id];
163
    }
164
165
    /**
166
     * Возвращает массив возможных значений свойств по property_id
167
     * Внимание! Это массивы, а не объекты!
168
     * Это сделано для экономии памяти.
169
     * Используется identity_map
170
     *
171
     * @return array
172
     */
173
    public static function getValuesForPropertyId($property_id)
174
    {
175
        if (!isset(static::$identity_map_by_property_id[$property_id])) {
176
            static::$identity_map_by_property_id[$property_id] = static::arrayOfValuesForPropertyId($property_id);
177
            foreach (static::$identity_map_by_property_id[$property_id] as $psv) {
178
                static::$identity_map[$psv['id']] = $psv;
179
            }
180
        }
181
        return static::$identity_map_by_property_id[$property_id];
182
    }
183
184
    public static function getSelectForPropertyId($property_id)
185
    {
186
        $values = PropertyStaticValues::getValuesForPropertyId($property_id);
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
187
        $result = [];
188
        foreach ($values as $row) {
189
            $result[$row['id']] = $row['name'];
190
        }
191
        return $result;
192
    }
193
194
    /**
195
     * @param $property_id
196
     * @param $category_id
197
     * @param $properties
198
     * @return PropertyStaticValues[]
199
     */
200
    public static function getValuesForFilter($property_id, $category_id, $properties, $multiple = false, $parentsOnly = true)
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 126 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
201
    {
202
        $priceMin = Yii::$app->request->get('price_min');
203
        $priceMax = Yii::$app->request->get('price_max');
204
        $cacheKey = "getValuesForFilter:" . json_encode([$property_id, $category_id, $properties, $priceMin, $priceMax]);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
205
        if (false === $allSelections = Yii::$app->cache->get($cacheKey)) {
206
            $joinCondition = (true === $parentsOnly) ?
207
                'p.id = {{%product_category}}.object_model_id AND p.active = 1 AND p.parent_id = 0'
208
                : 'p.id = {{%product_category}}.object_model_id AND p.active = 1';
209
            $objectModel = Object::getForClass(Product::className());
210
            $objectId = $objectModel !== null ? $objectModel->id : 0;
211
            $allSelections = static::find()
212
                ->asArray(true)
213
                ->select([self::tableName() . '.id', self::tableName() . '.name', 'value', self::tableName() . '.slug'])
214
                ->innerJoin(
215
                    ObjectStaticValues::tableName(),
216
                    ObjectStaticValues::tableName() . '.property_static_value_id=' . self::tableName() . '.id'
217
                )
218
                ->innerJoin(
219
                    '{{%product_category}}',
220
                    '{{%product_category}}.object_model_id = ' . ObjectStaticValues::tableName() . '.object_model_id'
221
                )
222
                ->innerJoin(
223
                    Product::tableName() . ' p',
224
                    $joinCondition
225
                )
226
                ->where(
227
                    [
228
                        self::tableName() . '.property_id' => $property_id,
229
                        self::tableName() . '.dont_filter' => 0,
230
                        '{{%product_category}}.category_id' => $category_id,
231
                    ]
232
                )
233
                ->orderBy(
234
                    [
235
                        self::tableName() . '.sort_order' => SORT_ASC,
236
                        self::tableName() . '.name' => SORT_ASC,
237
                    ]
238
                )
239
                ->all();
240
            /** @var ActiveQuery $query */
241
            $query = ObjectStaticValues::find()
242
                ->distinct(true)
243
                ->select(ObjectStaticValues::tableName() . '.object_model_id')
244
                ->where(['object_id' => $objectId]);
245
            if (false === empty($properties)) {
246
                foreach ($properties as $propertyId => $propertyStaticValues) {
247
                    $subQuery = self::initSubQuery($category_id, $joinCondition);
248
                    $subQuery->andWhere(['property_static_value_id' => $propertyStaticValues,]);
249 View Code Duplication
                    $subQueryOptimisation = Yii::$app->db->cache(function($db) use ($subQuery) {
250
                        $ids = implode(', ', $subQuery->createCommand($db)->queryColumn());
251
                        return empty($ids) === true ? '(-1)' : "($ids)";
252
                    }, 86400, new TagDependency([
253
                        'tags' => [
254
                            ActiveRecordHelper::getCommonTag(ObjectStaticValues::className()),
255
                        ]
256
                    ]));
257
                    $query->andWhere(new Expression('`object_model_id` IN ' . $subQueryOptimisation));
258
                }
259
            }
260
            if (false === empty($priceMin) && false === empty($priceMax)) {
261
                $subQuery = self::initSubQuery($category_id, $joinCondition);
262
                $subQuery
263
                    ->andWhere('p.price >= (:min_price * currency.convert_nominal / currency.convert_rate)',
264
                        [':min_price' => $priceMin])
265
                    ->andWhere('p.price <= (:max_price * currency.convert_nominal / currency.convert_rate)',
266
                        [':max_price' => $priceMax])
267
                    ->leftJoin(Currency::tableName() . ' ON currency.id = p.currency_id');
268 View Code Duplication
                $subQueryOptimisation = Yii::$app->db->cache(function($db) use ($subQuery) {
269
                    $ids = implode(', ', $subQuery->createCommand($db)->queryColumn());
270
                    return empty($ids) === true ? '(-1)' : "($ids)";
271
                }, 86400, new TagDependency([
272
                    'tags' => [
273
                        ActiveRecordHelper::getCommonTag(ObjectStaticValues::className()),
274
                    ]
275
                ]));
276
                $query->andWhere(new Expression('`object_model_id` IN ' . $subQueryOptimisation));
277
            }
278
            $selectedQuery = static::find()
279
                ->select(static::tableName() . '.id')
280
                ->asArray(true)
281
                ->innerJoin(
282
                    ObjectStaticValues::tableName(),
283
                    ObjectStaticValues::tableName() . '.property_static_value_id = ' . static::tableName() . '.id'
284
                )
285
                ->where([
286
                    'property_id' => $property_id,
287
                ])
288
                ->andWhere(
289
                    new Expression(
290
                        ObjectStaticValues::tableName() . '.object_model_id IN (' . $query->createCommand()->getRawSql() . ')'
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 126 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
291
                    )
292
                );
293
            if (false == $multiple) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
294
                if (isset($properties[$property_id])) {
295
                    $selectedQuery->andWhere([self::tableName() . '.id' => $properties[$property_id]]);
296
                }
297
            } else {
298
                unset($properties[$property_id]);
299
            }
300
            $selected = $selectedQuery->column();
301
            foreach ($allSelections as $index => $selection) {
302
                $allSelections[$index]['active'] = in_array($selection['id'], $selected);
303
            }
304 View Code Duplication
            if (null !== $allSelections) {
305
                Yii::$app->cache->set(
306
                    $cacheKey,
307
                    $allSelections,
308
                    0,
309
                    new TagDependency(
310
                        [
311
                            'tags' => [
312
                                ActiveRecordHelper::getCommonTag(PropertyStaticValues::className()),
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
313
                                ActiveRecordHelper::getCommonTag(Property::className()),
314
                            ]
315
316
                        ]
317
                    )
318
                );
319
            }
320
        }
321
        return $allSelections;
322
    }
323
324
    private static function initSubQuery($category_id, $joinCondition)
325
    {
326
        $subQuery = ObjectStaticValues::find();
327
        return $subQuery
328
            ->select(ObjectStaticValues::tableName() . '.object_model_id')
329
            ->innerJoin(
330
                '{{%product_category}}',
331
                '{{%product_category}}.object_model_id = ' . ObjectStaticValues::tableName() . '.object_model_id'
332
            )->innerJoin(
333
                Product::tableName() . ' p',
334
                $joinCondition
335
            )->where(
336
                [
337
                    'category_id' => $category_id,
338
                ]
339
            );
340
    }
341
    /**
342
     * Аналогично getValuesForPropertyId
343
     * Но identity_map не используется
344
     * @param int $property_id
345
     * @return array|mixed|\yii\db\ActiveRecord[]
346
     */
347
    public static function arrayOfValuesForPropertyId($property_id)
348
    {
349
        $cacheKey = "ValuesForProperty:$property_id";
350
351
        if (false === $values = Yii::$app->cache->get($cacheKey)) {
352
            $values = static::find()->where(['property_id' => $property_id])->orderBy(
353
                [
354
                    'sort_order' => SORT_ASC,
355
                    'name' => SORT_ASC
356
                ]
357
            )->asArray()->all();
358 View Code Duplication
            if (null !== $values) {
359
                Yii::$app->cache->set(
360
                    $cacheKey,
361
                    $values,
362
                    0,
363
                    new TagDependency(
364
                        [
365
                            'tags' => [
366
                                ActiveRecordHelper::getCommonTag(PropertyStaticValues::className()),
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
367
                                ActiveRecordHelper::getCommonTag(Property::className()),
368
                            ]
369
370
                        ]
371
                    )
372
                );
373
            }
374
        }
375
        return $values;
376
    }
377
378
    public function afterSave($insert, $changedAttributes)
379
    {
380
        if (null !== $parent = Property::findById($this->property_id)) {
381
            $parent->invalidateModelCache();
382
        }
383
        parent::afterSave($insert, $changedAttributes);
384
    }
385
386
    public function beforeDelete()
387
    {
388
        if (null !== $parent = Property::findById($this->property_id)) {
389
            $parent->invalidateModelCache();
390
        }
391
        return parent::beforeDelete();
392
    }
393
394
    public function afterDelete()
395
    {
396
        ObjectStaticValues::deleteAll(['property_static_value_id' => $this->id]);
397
        parent::afterDelete();
398
    }
399
}
400