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.
Test Setup Failed
Push — action_getCatTree_order ( 77944b )
by
unknown
23:56
created

ThemeParts::renderPart()   C

Complexity

Conditions 11
Paths 21

Size

Total Lines 90
Code Lines 59

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
dl 0
loc 90
rs 5.2653
c 2
b 0
f 0
cc 11
eloc 59
nc 21
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
     * Workaround for php 7
120
     *
121
     * In php7 json_decode(null) produces JSON_ERROR_SYNTAX
122
     *
123
     * @todo rewrite all json_decode calls in that manner
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
124
     *
125
     * @param null $json
126
     * @return null|string
127
     */
128
    private static function _php7JsonPatch($json = null)
129
    {
130
        return $json === null ? '[]' : $json;
131
    }
132
133
    /**
134
     * Renders specified theme part with all it's widget corresponding current theme variation
135
     * @param string $key Theme part key(ie. header or pre-footer)
136
     * @param array $params
137
     * @return string
138
     * @throws InvalidConfigException
139
     */
140
    public static function renderPart($key, $params=[])
141
    {
142
        $parts = static::getAllParts();
143
        Yii::beginProfile('Render theme part:' . $key);
144
        Yii::trace('Render theme part:' . $key);
145
        /** @var array $model */
146
        $model = null;
147
        foreach ($parts as $part) {
148
            if ($part['key'] === $key) {
149
                $model = $part;
150
                break;
151
            }
152
        }
153
        if ($model === null) {
154
            throw new InvalidConfigException("Can't find part with key $key");
155
        }
156
157
        /** @var ViewElementsGathener $viewElementsGathener */
158
        $viewElementsGathener = Yii::$app->viewElementsGathener;
159
160
161
        if (static::shouldCache($model)) {
162
            $result = Yii::$app->cache->get(static::getCacheKey($model));
163
            if ($result !== false) {
164
                Yii::endProfile('Render theme part:' . $key);
165
                $cachedData = $viewElementsGathener->getCachedData('ThemePart:'.$key);
166
                if (is_array($cachedData)) {
167
                    $viewElementsGathener->repeatGatheredData(Yii::$app->view, $cachedData);
168
                }
169
                return $result;
170
            }
171
            $viewElementsGathener->startGathering(
172
                'ThemePart:'.$key,
173
                static::getCacheDependency($model)
174
            );
175
        }
176
177
        $model['id'] = intval($model['id']);
178
179
        $widgets = array_reduce(
180
            ThemeActiveWidgets::getActiveWidgets(),
181
            function ($carry, $item) use($model) {
182
                if ($item['part_id'] === $model['id']) {
183
                    $carry[]=$item;
184
                }
185
                return $carry;
186
            },
187
            []
188
        );
189
        ArrayHelper::multisort($widgets, 'sort_order');
190
191
        $result = array_reduce(
192
            $widgets,
193
            function($carry, ThemeActiveWidgets $activeWidget) use ($model, $params) {
194
                /** @var ThemeWidgets $widgetModel */
195
                $widgetModel = $activeWidget->widget;
196
                /** @var BaseWidget $widgetClassName */
197
                $widgetClassName =  $widgetModel->widget;
198
                $widgetConfiguration = Json::decode(self::_php7JsonPatch($widgetModel->configuration_json), true);
199
                if (!is_array($widgetConfiguration)) {
200
                    $widgetConfiguration = [];
201
                }
202
                $activeWidgetConfiguration = Json::decode(self::_php7JsonPatch($activeWidget->configuration_json), true);
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...
203
                if (!is_array($activeWidgetConfiguration)) {
204
                    $activeWidgetConfiguration  = [];
205
                }
206
                $merged = ArrayHelper::merge($widgetConfiguration, $activeWidgetConfiguration);
207
                $config = ArrayHelper::merge($merged, $params);
208
                $config['themeWidgetModel'] = $widgetModel;
209
                $config['partRow'] = $model;
210
                $config['activeWidget'] = $activeWidget;
211
212
                $carry .= $widgetClassName::widget($config);
213
                return $carry;
214
            },
215
            ''
216
        );
217
218
        if (static::shouldCache($model)) {
219
            Yii::$app->cache->set(
220
                static::getCacheKey($model),
221
                $result,
222
                $model['cache_lifetime'],
223
                static::getCacheDependency($model)
224
            );
225
            $viewElementsGathener->endGathering();
226
        }
227
        Yii::endProfile('Render theme part:' . $key);
228
        return $result;
229
    }
230
231
    /**
232
     * @param array $attributesRow
233
     * @return bool True if we should cache this widget
234
     */
235
    public static function shouldCache($attributesRow)
236
    {
237
        return intval($attributesRow['is_cacheable'])=== 1 && $attributesRow['cache_lifetime']> 0;
238
    }
239
240
    /**
241
     * @param array $attributesRow
242
     * @return string Cache key for this widget
243
     */
244
    public static function getCacheKey($attributesRow)
245
    {
246
        $guestVary = Yii::$app->user->isGuest ? '1' : '0';
247
        $sessionVary = $attributesRow['cache_vary_by_session'] ? ':' . Yii::$app->session->id . ':' . $guestVary : '';
248
        $cacheKey = "ThemePartCache:".$attributesRow['id'] . $sessionVary;
249
        return $cacheKey;
250
    }
251
252
    /**
253
     * @param array $attributesRow
254
     * @return string[] Array of cache tags
255
     */
256
    public static function getCacheTags($attributesRow)
257
    {
258
        $tags = explode("\n", $attributesRow['cache_tags']);
259
        $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...
260
        $tags[] = ActiveRecordHelper::getCommonTag(ThemeActiveWidgets::className());
261
        return $tags;
262
    }
263
264
    /**
265
     * @param array $attributesRow
266
     * @return TagDependency TagDependency for cache storing
267
     */
268
    public static function getCacheDependency($attributesRow)
269
    {
270
        return new TagDependency([
271
            'tags' => static::getCacheTags($attributesRow),
272
        ]);
273
    }
274
275
    /**
276
     * Search
277
     * @param $params
278
     * @return ActiveDataProvider
279
     */
280
    public function search($params)
281
    {
282
        /* @var $query \yii\db\ActiveQuery */
283
        $query = self::find();
284
        $dataProvider = new ActiveDataProvider(
285
            [
286
                'query' => $query,
287
                'pagination' => [
288
                    'pageParam' => 'part-page',
289
                    'pageSizeParam' => 'part-per-page',
290
                ],
291
            ]
292
        );
293
        if (!($this->load($params))) {
294
            return $dataProvider;
295
        }
296
        $query->andFilterWhere(['id' => $this->id]);
297
        $query->andFilterWhere(['global_visibility' => $this->global_visibility]);
298
        $query->andFilterWhere(['is_cacheable' => $this->is_cacheable]);
299
        $query->andFilterWhere(['cache_vary_by_session' => $this->cache_vary_by_session]);
300
        $query->andFilterWhere(['like', 'name', $this->name]);
301
        $query->andFilterWhere(['like', 'key', $this->key]);
302
303
        return $dataProvider;
304
    }
305
306
    /**
307
     * @inheritdoc
308
     */
309 View Code Duplication
    public function beforeDelete()
310
    {
311
        if (!parent::beforeDelete()) {
312
            return false;
313
        }
314
315
        $activeParts = ThemeWidgetApplying::find()->where(['part_id'=>$this->id])->all();
316
        foreach ($activeParts as $part) {
317
            $part->delete();
318
        }
319
320
        $activeWidgets = ThemeActiveWidgets::find()->where(['widget_id'=>$this->id])->all();
321
        foreach ($activeWidgets as $widget) {
322
            $widget->delete();
323
        }
324
325
        return true;
326
    }
327
}
328