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 ( c721cc...3ff35f )
by Ivan
09:59
created

ThemeParts   B

Complexity

Total Complexity 32

Size/Duplication

Total Lines 284
Duplicated Lines 11.97 %

Coupling/Cohesion

Components 1
Dependencies 15

Importance

Changes 0
Metric Value
wmc 32
lcom 1
cbo 15
dl 34
loc 284
rs 8.8
c 0
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
A behaviors() 0 8 1
A tableName() 0 4 1
A rules() 0 8 1
A attributeLabels() 0 14 1
B getAllParts() 16 28 4
A shouldCache() 0 4 2
A getCacheKey() 0 7 3
A getCacheTags() 0 7 1
A getCacheDependency() 0 6 1
B search() 0 25 2
A beforeDelete() 18 18 4
C renderPart() 0 90 11

How to fix   Duplicated Code   

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:

1
<?php
2
3
namespace app\extensions\DefaultTheme\models;
4
5
use app\components\ViewElementsGathener;
6
use app\extensions\DefaultTheme\components\BaseWidget;
7
use app\traits\IdentityMap;
8
use Yii;
9
use yii\base\InvalidConfigException;
10
use yii\caching\TagDependency;
11
use \devgroup\TagDependencyHelper\ActiveRecordHelper;
12
use yii\helpers\ArrayHelper;
13
use yii\data\ActiveDataProvider;
14
use yii\helpers\Json;
15
16
/**
17
 * This is the model class for table "{{%theme_parts}}".
18
 *
19
 * @property integer $id
20
 * @property string $name
21
 * @property string $key
22
 * @property integer $global_visibility
23
 * @property integer $multiple_widgets
24
 * @property integer $is_cacheable
25
 * @property integer $cache_lifetime
26
 * @property string $cache_tags
27
 * @property integer $cache_vary_by_session
28
 */
29
class ThemeParts extends \yii\db\ActiveRecord
30
{
31
    use IdentityMap;
32
    public static $allParts = null;
33
    /**
34
     * @inheritdoc
35
     */
36
    public function behaviors()
37
    {
38
        return [
39
            [
40
                'class' => ActiveRecordHelper::className(),
41
            ],
42
        ];
43
    }
44
45
    /**
46
     * @inheritdoc
47
     */
48
    public static function tableName()
49
    {
50
        return '{{%theme_parts}}';
51
    }
52
53
    /**
54
     * @inheritdoc
55
     */
56
    public function rules()
57
    {
58
        return [
59
            [['global_visibility', 'multiple_widgets', 'is_cacheable', 'cache_lifetime', 'cache_vary_by_session'], 'integer'],
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...
60
            [['cache_tags'], 'string'],
61
            [['name', 'key'], 'string', 'max' => 255]
62
        ];
63
    }
64
65
    /**
66
     * @inheritdoc
67
     */
68
    public function attributeLabels()
69
    {
70
        return [
71
            'id' => Yii::t('app', 'ID'),
72
            'name' => Yii::t('app', 'Name'),
73
            'key' => Yii::t('app', 'Key'),
74
            'global_visibility' => Yii::t('app', 'Global Visibility'),
75
            'multiple_widgets' => Yii::t('app', 'Multiple Widgets'),
76
            'is_cacheable' => Yii::t('app', 'Is Cacheable'),
77
            'cache_lifetime' => Yii::t('app', 'Cache Lifetime'),
78
            'cache_tags' => Yii::t('app', 'Cache Tags'),
79
            'cache_vary_by_session' => Yii::t('app', 'Cache Vary By Session'),
80
        ];
81
    }
82
83
    /**
84
     * Returns all db-stored theme parts in array representation
85
     *
86
     * @param bool $force True if you want to refresh static-variable cache
87
     * @return array
88
     */
89
    public static function getAllParts($force = false)
90
    {
91
        if (static::$allParts=== null || $force === true) {
92
            $cacheKey = 'AllThemeParts';
93
94
            Yii::beginProfile('Get all theme parts');
95
96
            static::$allParts= Yii::$app->cache->get($cacheKey);
97 View Code Duplication
            if (static::$allParts=== false) {
98
                static::$allParts= ThemeParts::find()
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...
99
                    ->where(['global_visibility'=>1])
100
                    ->asArray()
101
                    ->all();
102
                Yii::$app->cache->set(
103
                    $cacheKey,
104
                    static::$allParts,
105
                    86400,
106
                    new TagDependency([
107
                        'tags' => [
108
                            ActiveRecordHelper::getCommonTag(ThemeVariation::className()),
109
                        ]
110
                    ])
111
                );
112
            }
113
            Yii::endProfile('Get all theme parts');
114
        }
115
        return static::$allParts;
116
    }
117
118
    /**
119
     * Renders specified theme part with all it's widget corresponding current theme variation
120
     * @param string $key Theme part key(ie. header or pre-footer)
121
     * @param array $params
122
     * @return string
123
     * @throws InvalidConfigException
124
     */
125
    public static function renderPart($key, $params=[])
126
    {
127
        $parts = static::getAllParts();
128
        Yii::beginProfile('Render theme part:' . $key);
129
        Yii::trace('Render theme part:' . $key);
130
        /** @var array $model */
131
        $model = null;
132
        foreach ($parts as $part) {
133
            if ($part['key'] === $key) {
134
                $model = $part;
135
                break;
136
            }
137
        }
138
        if ($model === null) {
139
            throw new InvalidConfigException("Can't find part with key $key");
140
        }
141
142
        /** @var ViewElementsGathener $viewElementsGathener */
143
        $viewElementsGathener = Yii::$app->viewElementsGathener;
144
145
146
        if (static::shouldCache($model)) {
147
            $result = Yii::$app->cache->get(static::getCacheKey($model));
148
            if ($result !== false) {
149
                Yii::endProfile('Render theme part:' . $key);
150
                $cachedData = $viewElementsGathener->getCachedData('ThemePart:'.$key);
151
                if (is_array($cachedData)) {
152
                    $viewElementsGathener->repeatGatheredData(Yii::$app->view, $cachedData);
153
                }
154
                return $result;
155
            }
156
            $viewElementsGathener->startGathering(
157
                'ThemePart:'.$key,
158
                static::getCacheDependency($model)
159
            );
160
        }
161
162
        $model['id'] = intval($model['id']);
163
164
        $widgets = array_reduce(
165
            ThemeActiveWidgets::getActiveWidgets(),
166
            function ($carry, $item) use($model) {
167
                if ($item['part_id'] === $model['id']) {
168
                    $carry[]=$item;
169
                }
170
                return $carry;
171
            },
172
            []
173
        );
174
        ArrayHelper::multisort($widgets, 'sort_order');
175
176
        $result = array_reduce(
177
            $widgets,
178
            function($carry, ThemeActiveWidgets $activeWidget) use ($model, $params) {
179
                /** @var ThemeWidgets $widgetModel */
180
                $widgetModel = $activeWidget->widget;
181
                /** @var BaseWidget $widgetClassName */
182
                $widgetClassName =  $widgetModel->widget;
183
                $widgetConfiguration = Json::decode($widgetModel->configuration_json, true);
184
                if (!is_array($widgetConfiguration)) {
185
                    $widgetConfiguration = [];
186
                }
187
                $activeWidgetConfiguration = Json::decode($activeWidget->configuration_json, true);
188
                if (!is_array($activeWidgetConfiguration)) {
189
                    $activeWidgetConfiguration  = [];
190
                }
191
                $merged = ArrayHelper::merge($widgetConfiguration, $activeWidgetConfiguration);
192
                $config = ArrayHelper::merge($merged, $params);
193
                $config['themeWidgetModel'] = $widgetModel;
194
                $config['partRow'] = $model;
195
                $config['activeWidget'] = $activeWidget;
196
197
                $carry .= $widgetClassName::widget($config);
198
                return $carry;
199
            },
200
            ''
201
        );
202
203
        if (static::shouldCache($model)) {
204
            Yii::$app->cache->set(
205
                static::getCacheKey($model),
206
                $result,
207
                $model['cache_lifetime'],
208
                static::getCacheDependency($model)
209
            );
210
            $viewElementsGathener->endGathering();
211
        }
212
        Yii::endProfile('Render theme part:' . $key);
213
        return $result;
214
    }
215
216
    /**
217
     * @param array $attributesRow
218
     * @return bool True if we should cache this widget
219
     */
220
    public static function shouldCache($attributesRow)
221
    {
222
        return intval($attributesRow['is_cacheable'])=== 1 && $attributesRow['cache_lifetime']> 0;
223
    }
224
225
    /**
226
     * @param array $attributesRow
227
     * @return string Cache key for this widget
228
     */
229
    public static function getCacheKey($attributesRow)
230
    {
231
        $guestVary = Yii::$app->user->isGuest ? '1' : '0';
232
        $sessionVary = $attributesRow['cache_vary_by_session'] ? ':' . Yii::$app->session->id . ':' . $guestVary : '';
233
        $cacheKey = "ThemePartCache:".$attributesRow['id'] . $sessionVary;
234
        return $cacheKey;
235
    }
236
237
    /**
238
     * @param array $attributesRow
239
     * @return string[] Array of cache tags
240
     */
241
    public static function getCacheTags($attributesRow)
242
    {
243
        $tags = explode("\n", $attributesRow['cache_tags']);
244
        $tags[] = ActiveRecordHelper::getObjectTag(ThemeParts::className(), $attributesRow['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...
245
        $tags[] = ActiveRecordHelper::getCommonTag(ThemeActiveWidgets::className());
246
        return $tags;
247
    }
248
249
    /**
250
     * @param array $attributesRow
251
     * @return TagDependency TagDependency for cache storing
252
     */
253
    public static function getCacheDependency($attributesRow)
254
    {
255
        return new TagDependency([
256
            'tags' => static::getCacheTags($attributesRow),
257
        ]);
258
    }
259
260
    /**
261
     * Search
262
     * @param $params
263
     * @return ActiveDataProvider
264
     */
265
    public function search($params)
266
    {
267
        /* @var $query \yii\db\ActiveQuery */
268
        $query = self::find();
269
        $dataProvider = new ActiveDataProvider(
270
            [
271
                'query' => $query,
272
                'pagination' => [
273
                    'pageParam' => 'part-page',
274
                    'pageSizeParam' => 'part-per-page',
275
                ],
276
            ]
277
        );
278
        if (!($this->load($params))) {
279
            return $dataProvider;
280
        }
281
        $query->andFilterWhere(['id' => $this->id]);
282
        $query->andFilterWhere(['global_visibility' => $this->global_visibility]);
283
        $query->andFilterWhere(['is_cacheable' => $this->is_cacheable]);
284
        $query->andFilterWhere(['cache_vary_by_session' => $this->cache_vary_by_session]);
285
        $query->andFilterWhere(['like', 'name', $this->name]);
286
        $query->andFilterWhere(['like', 'key', $this->key]);
287
288
        return $dataProvider;
289
    }
290
291
    /**
292
     * @inheritdoc
293
     */
294 View Code Duplication
    public function beforeDelete()
295
    {
296
        if (!parent::beforeDelete()) {
297
            return false;
298
        }
299
300
        $activeParts = ThemeWidgetApplying::find()->where(['part_id'=>$this->id])->all();
301
        foreach ($activeParts as $part) {
302
            $part->delete();
303
        }
304
305
        $activeWidgets = ThemeActiveWidgets::find()->where(['widget_id'=>$this->id])->all();
306
        foreach ($activeWidgets as $widget) {
307
            $widget->delete();
308
        }
309
310
        return true;
311
    }
312
}
313