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 — filters ( 6ca298...bd9ca2 )
by Ivan
09:38
created

ContentBlockHelper::sanitizeChunk()   B

Complexity

Conditions 6
Paths 17

Size

Total Lines 24
Code Lines 17

Duplication

Lines 6
Ratio 25 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 6
loc 24
rs 8.5126
c 1
b 0
f 0
cc 6
eloc 17
nc 17
nop 1
1
<?php
2
namespace app\modules\core\helpers;
3
4
use app\models\Property;
5
use app\models\PropertyStaticValues;
6
use app\modules\core\models\ContentBlock;
7
use app\modules\shop\models\Product;
8
use devgroup\TagDependencyHelper\ActiveRecordHelper;
9
use yii\caching\TagDependency;
10
use yii\helpers\ArrayHelper;
11
use yii\helpers\Url;
12
use yii;
13
use app;
14
15
/**
16
 * Class ContentBlockHelper
17
 * Main public static method compileContentString() uses submethods to extract chunk calls from model content field,
18
 * fetch chunks from data base table, then compile it and replace chunk calls with compiled chunks data
19
 * Example chunk call in model content field should be like: [[$chunk param='value'|'default value' param2=42]].
20
 * Chunk declaration should be like : <p>String: [[+param]]</p> <p>Float: [[+param2:format, param1, param2]]</p>
21
 * All supported formats you can find at Yii::$app->formatter
22
 *
23
 * @package app\modules\core\helpers
24
 */
25
class ContentBlockHelper
26
{
27
    private static $chunksByKey = [];
28
29
    /**
30
     * Compiles content string by injecting chunks into content
31
     * Preloads chunks which have preload = 1
32
     *
33
     * @param  string $content Original content with chunk calls
34
     * @param  string $content_key Key for caching compiled content version
35
     * @param  yii\caching\Dependency $dependency Cache dependency
36
     * @return string Compiled content with injected chunks
37
     */
38
    public static function compileContentString($content, $content_key, $dependency)
39
    {
40
        self::preloadChunks();
41
        $output = self::processData($content, $content_key, $dependency);
42
        $output = self::processData($output, $content_key, $dependency, '', false);
43
        return $output;
44
    }
45
46
    /**
47
     * Finding chunk calls with regexp
48
     * Iterate matches
49
     * While iterating:
50
     * Extracts single chunk data with sanitizeChunk() method
51
     * Fetches chunk by key using fetchChunkByKey(), who returns chunk value by key from static array if exists, otherwise from db
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 130 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...
52
     * Compiles single chunk using compileChunk() method
53
     * Replaces single chunk call with compiled chunk data in the model content
54
     *
55
     * @param  string $content_key Key for caching compiled content version
56
     * @param  yii\caching\Dependency $dependency Cache dependency
57
     * @param  bool $preprocess flag to separate rendering non cacheable chunks such as Form
58
     * @param  string $content
59
     * @param  string $chunk_key ContentBlock key string to prevent endless recursion
60
     * @return string
61
     */
62
    private static function processData($content, $content_key, $dependency, $chunk_key = '', $preprocess = true)
63
    {
64
        $matches = [];
65
        $replacement = '';
66
        preg_match_all('%\[\[([^\]\[]+)\]\]%ui', $content, $matches);
67
        if (!empty($matches[0])) {
68
            foreach ($matches[0] as $k => $rawChunk) {
69
                $chunkData = self::sanitizeChunk($rawChunk);
70
                if ($chunkData['key'] == $chunk_key) {
71
                    $content = str_replace($matches[0][$k], '', $content);
72
                    continue;
73
                }
74
                $cacheKey = $content_key . $chunkData['key'] . serialize($chunkData);
75
                switch ($chunkData['token']) {
76
                    case '$':
77
                        if ($preprocess === false) break;
78
                        $chunk = self::fetchChunkByKey($chunkData['key']);
79
                        $replacement = Yii::$app->cache->get($cacheKey);
80
                        if ($replacement === false) {
81
                            $replacement = static::compileChunk($chunk, $chunkData, $chunkData['key'], $content_key, $dependency);
0 ignored issues
show
Bug introduced by
Since compileChunk() is declared private, calling it with static will lead to errors in possible sub-classes. You can either use self, or increase the visibility of compileChunk() to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
}

public static function getSomeVariable()
{
    return static::getTemperature();
}

}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass {
      private static function getTemperature() {
        return "-182 °C";
    }
}

print YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
    }

    public static function getSomeVariable()
    {
        return self::getTemperature();
    }
}
Loading history...
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 130 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...
82
                            Yii::$app->cache->set(
83
                                $content_key,
84
                                $replacement,
85
                                84600,
86
                                $dependency
87
                            );
88
                        }
89
                        break;
90
                    case '%':
91
                        if ($preprocess === true) {
92
                            $replacement = $rawChunk;
93
                            break;
94
                        }
95
                        $replacement = static::replaceForms($chunkData);
0 ignored issues
show
Bug introduced by
Since replaceForms() is declared private, calling it with static will lead to errors in possible sub-classes. You can either use self, or increase the visibility of replaceForms() to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
}

public static function getSomeVariable()
{
    return static::getTemperature();
}

}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass {
      private static function getTemperature() {
        return "-182 °C";
    }
}

print YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
    }

    public static function getSomeVariable()
    {
        return self::getTemperature();
    }
}
Loading history...
96
                        break;
97 View Code Duplication
                    case '~' :
1 ignored issue
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
Duplication introduced by
This code seems to be duplicated across 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...
98
                        if ($preprocess === false) break;
99
                        $replacement = Yii::$app->cache->get($cacheKey);
100
                        if ($replacement === false) {
101
                            $replacement = static::renderUrl($chunkData);
0 ignored issues
show
Bug introduced by
Since renderUrl() is declared private, calling it with static will lead to errors in possible sub-classes. You can either use self, or increase the visibility of renderUrl() to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
}

public static function getSomeVariable()
{
    return static::getTemperature();
}

}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass {
      private static function getTemperature() {
        return "-182 °C";
    }
}

print YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
    }

    public static function getSomeVariable()
    {
        return self::getTemperature();
    }
}
Loading history...
102
                            Yii::$app->cache->set(
103
                                $content_key,
104
                                $replacement,
105
                                84600,
106
                                $dependency
107
                            );
108
                        }
109
                        break;
110 View Code Duplication
                    case '*':
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across 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...
111
                        if ($preprocess === false) {
112
                            break;
113
                        }
114
                        $replacement = Yii::$app->cache->get($cacheKey);
115
                        if ($replacement === false) {
116
                            $replacement = static::renderProducts($chunkData, $dependency);
0 ignored issues
show
Bug introduced by
Since renderProducts() is declared private, calling it with static will lead to errors in possible sub-classes. You can either use self, or increase the visibility of renderProducts() to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
}

public static function getSomeVariable()
{
    return static::getTemperature();
}

}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass {
      private static function getTemperature() {
        return "-182 °C";
    }
}

print YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
    }

    public static function getSomeVariable()
    {
        return self::getTemperature();
    }
}
Loading history...
117
                            Yii::$app->cache->set(
118
                                $content_key,
119
                                $replacement,
120
                                84600,
121
                                $dependency
122
                            );
123
                        }
124
                        break;
125
                }
126
                $content = str_replace($matches[0][$k], $replacement, $content);
127
            }
128
        }
129
        return $content;
130
    }
131
132
    /**
133
     * @param array $chunkData
134
     * @return mixed
135
     */
136
    private static function replaceForms($chunkData)
137
    {
138
        $regexp = '/^(?P<formId>\d+)(#(?P<id>[\w\d\-_]+))?(;(?P<isModal>isModal))?$/Usi';
139
        return preg_replace_callback(
140
            $regexp,
141
            function ($matches) {
142
                if (isset($matches['formId'])) {
143
                    $params = ['formId' => intval($matches['formId'])];
144
                    if (isset($matches['id'])) {
145
                        $params['id'] = $matches['id'];
146
                    }
147
                    if (isset($matches['isModal'])) {
148
                        $params['isModal'] = true;
149
                    }
150
                    return app\widgets\form\Form::widget($params);
151
                }
152
                return '';
153
            },
154
            $chunkData['key']
155
        );
156
    }
157
158
    /**
159
     * renders url according to given data
160
     * @param $chunkData
161
     * @return string
162
     */
163
    private static function renderUrl($chunkData)
164
    {
165
        $expression = '%(?P<objectName>[^#]+?)#(?P<objectId>[\d]+?)$%';
166
        $output = '';
167
        preg_match($expression, $chunkData['key'], $m);
168
        if (true === isset($m['objectName'], $m['objectId'])) {
169
            $id = (int)$m['objectId'];
170
            switch (strtolower($m['objectName'])) {
171 View Code Duplication
                case "page" :
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across 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...
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
172
                    if (null !== $model = app\modules\page\models\Page::findById($id)) {
173
                        $output = Url::to(['@article', 'id' => $id]);
174
                    }
175
                    break;
176
                case "category" :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
177
                    if (null !== $model = app\modules\shop\models\Category::findById($id)) {
178
                        $output = Url::to(['@category', 'last_category_id' => $id]);
179
                    }
180
                    break;
181 View Code Duplication
                case "product" :
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across 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...
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
182
                    if (null !== $model = app\modules\shop\models\Product::findById($id)) {
183
                        $output = Url::to(['@product', 'model' => $model]);
184
                    }
185
                    break;
186
            }
187
        }
188
        return $output;
189
    }
190
191
    /**
192
     * Extracts chunk data from chunk call
193
     * uses regexp to extract param data from placeholder
194
     * [[$chunk <paramName>='<escapedValue>'|'<escapedDefault>' <paramName>=<unescapedValue>|<unescapedDefault>]]
195
     * iterate matches.
196
     * While iterating converts escapedValue and escapedDefault into string, unescapedValue and unescapedDefault - into float
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 125 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...
197
     * Returns chunk data array like:
198
     *  [
199
     *      'key' => 'chunkKey',
200
     *      'firstParam'=> 'string value',
201
     *      'firstParam-default'=> 'default string value',
202
     *      'secondParam'=> float value,
203
     *      'secondParam-default'=> default float value,
204
     *  ]
205
     *
206
     * @param string $rawChunk
207
     * @return array
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array<*,string|double>.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
208
     */
209
    private static function sanitizeChunk($rawChunk)
210
    {
211
        $chunk = [];
212
        preg_match('%(?P<chunkToken>[^\w\[]?)([^\s\]\[]+)[\s\]]%', $rawChunk, $keyMatches);
213
        $chunk['token'] = $keyMatches['chunkToken'];
214
        $chunk['key'] = $keyMatches[2];
215
        $expression = "#\s*(?P<paramName>[\\w\\d]*)=(('(?P<escapedValue>.*[^\\\\])')|(?P<unescapedValue>.*))(\\|(('(?P<escapedDefault>.*[^\\\\])')|(?P<unescapedDefault>.*)))?[\\]\\s]#uUi";
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 188 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...
216
        preg_match_all($expression, $rawChunk, $matches);
217
        foreach ($matches['paramName'] as $key => $paramName) {
218
            if (!empty($matches['escapedValue'][$key])) {
219
                $chunk[$paramName] = strval($matches['escapedValue'][$key]);
220
            }
221
            if (!empty($matches['unescapedValue'][$key])) {
222
                $chunk[$paramName] = floatval($matches['unescapedValue'][$key]);
223
            }
224 View Code Duplication
            if (!empty($matches['escapedDefault'][$key])) {
225
                $chunk[$paramName . '-default'] = strval($matches['escapedDefault'][$key]);
226
            }
227 View Code Duplication
            if (!empty($matches['unescapedDefault'][$key])) {
228
                $chunk[$paramName . '-default'] = floatval($matches['unescapedDefault'][$key]);
229
            }
230
        }
231
        return $chunk;
232
    }
233
234
    /**
235
     * Compiles single chunk
236
     * uses regexp to find placeholders and extract it's data from chunk value field
237
     * [[<token><paramName>:<format><params>]]
238
     * token switch is for future functionality increase
239
     * now method only recognizes + token and replaces following param with according $arguments array data
240
     * applies formatter according previously defined param values type if needed
241
     * if param name from placeholder was not found in arguments array, placeholder in the compiled chunk will be replaced with empty string
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 140 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...
242
     * returns compiled chunk
243
     *
244
     * @param  string $content_key Key for caching compiled content version
245
     * @param  yii\caching\Dependency $dependency Cache dependency
246
     * @param  string $chunk ContentBlock instance
247
     * @param  array $arguments Arguments for this chunk from original content
248
     * @param  string $key ContentBlock key string to prevent endless recursion
249
     * @return string Result string ready for replacing
250
     */
251
    private static function compileChunk($chunk, $arguments, $key, $content_key, $dependency)
252
    {
253
        $matches = [];
254
        preg_match_all('%\[\[(?P<token>[\+\*])(?P<paramName>[^\s\:\]]+)\:?(?P<format>[^\,\]]+)?\,?(?P<params>[^\]]+)?\]\]%ui', $chunk, $matches);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 145 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...
255
        foreach ($matches[0] as $k => $rawParam) {
256
            $token = $matches['token'][$k];
257
            $paramName = trim($matches['paramName'][$k]);
258
            $format = trim($matches['format'][$k]);
259
            $params = preg_replace('%[\s]%', '', $matches['params'][$k]);
260
            $params = explode(',', $params);
261
            switch ($token) {
262
                case '+':
263
                    if (array_key_exists($paramName, $arguments)) {
264
                        $replacement = static::applyFormatter($arguments[$paramName], $format, $params);
0 ignored issues
show
Bug introduced by
Since applyFormatter() is declared private, calling it with static will lead to errors in possible sub-classes. You can either use self, or increase the visibility of applyFormatter() to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
}

public static function getSomeVariable()
{
    return static::getTemperature();
}

}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass {
      private static function getTemperature() {
        return "-182 °C";
    }
}

print YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
    }

    public static function getSomeVariable()
    {
        return self::getTemperature();
    }
}
Loading history...
265
                        $chunk = str_replace($matches[0][$k], $replacement, $chunk);
266
                    } else if (array_key_exists($paramName . '-default', $arguments)) {
267
                        $replacement = static::applyFormatter($arguments[$paramName . '-default'], $format, $params);
0 ignored issues
show
Bug introduced by
Since applyFormatter() is declared private, calling it with static will lead to errors in possible sub-classes. You can either use self, or increase the visibility of applyFormatter() to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
}

public static function getSomeVariable()
{
    return static::getTemperature();
}

}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass {
      private static function getTemperature() {
        return "-182 °C";
    }
}

print YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
    }

    public static function getSomeVariable()
    {
        return self::getTemperature();
    }
}
Loading history...
268
                        $chunk = str_replace($matches[0][$k], $replacement, $chunk);
269
                    } else {
270
                        $chunk = str_replace($matches[0][$k], '', $chunk);
271
                    }
272
                    break;
273
                default:
274
                    $chunk = str_replace($matches[0][$k], '', $chunk);
275
            }
276
        }
277
        return self::processData($chunk, $content_key, $dependency, $key);
278
    }
279
280
    /**
281
     * Find formatter declarations in chunk placeholders. if find trying to apply
282
     * yii\i18n\Formatter formats see yii\i18n\Formatter for details
283
     *
284
     * @param string $value single placeholder declaration from chunk
285
     * @param string $format
286
     * @param array $params
287
     * @return string|array
288
     */
289
    private static function applyFormatter($value, $format, $params)
290
    {
291
        if (false === method_exists(Yii::$app->formatter, $format) || empty($format)) {
292
            return $value;
293
        }
294
        array_unshift($params, $value);
295
        try {
296
            $formattedValue = call_user_func_array([Yii::$app->formatter, $format], $params);
297
        } catch (\Exception $e) {
298
            $formattedValue = $value;
299
        }
300
        return $formattedValue;
301
    }
302
303
    /**
304
     * Fetches single chunk by key from static var
305
     * if is no there - get it from db and push to static array
306
     *
307
     * @param $key string Chunk key field
308
     * @return string Chunk value field
309
     */
310
    private static function fetchChunkByKey($key)
311
    {
312
        if (!array_key_exists($key, static::$chunksByKey)) {
313
            $dependency = new TagDependency([
314
                'tags' => [
315
                    ActiveRecordHelper::getCommonTag(ContentBlock::className()),
316
                ]
317
            ]);
318
            static::$chunksByKey[$key] = ContentBlock::getDb()->cache(function ($db) use ($key) {
0 ignored issues
show
Unused Code introduced by
The parameter $db 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...
319
                $chunk = ContentBlock::find()
320
                    ->where(['key' => $key])
321
                    ->asArray()
322
                    ->one();
323
                return static::$chunksByKey[$key] = $chunk['value'];
324
            }, 86400, $dependency);
325
        }
326
        return static::$chunksByKey[$key];
327
    }
328
329
    /**
330
     * preloads chunks with option preload  = 1
331
     * and push it to static array
332
     *
333
     * @return array|void
334
     */
335
    private static function preloadChunks()
336
    {
337
        if (is_null(static::$chunksByKey)) {
338
            $dependency = new TagDependency([
339
                'tags' => [
340
                    ActiveRecordHelper::getCommonTag(ContentBlock::className()),
341
                ]
342
            ]);
343
            static::$chunksByKey = ContentBlock::getDb()->cache(function ($db) {
0 ignored issues
show
Unused Code introduced by
The parameter $db 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...
344
                $chunks = ContentBlock::find()
345
                    ->where(['preload' => 1])
346
                    ->asArray()
347
                    ->all();
348
                return ArrayHelper::map($chunks, 'key', 'value');
349
            }, 86400, $dependency);
350
        }
351
        return static::$chunksByKey;
352
    }
353
354
    /**
355
     * renders chunks in template files
356
     * @param string $key ContentBlock key
357
     * @param array $params . Array of params to be replaced while render
358
     * @param yii\base\Model $model . Caller model instance to use in caching
0 ignored issues
show
Documentation introduced by
Should the type for parameter $model not be null|yii\base\Model?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
359
     * @return mixed
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use string.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
360
     */
361
    public static function getChunk($key, $params = [], yii\base\Model $model = null)
362
    {
363
        if (null === $rawChunk = self::fetchChunkByKey($key)) {
364
            return '';
365
        }
366
        $tags = [
367
            ActiveRecordHelper::getCommonTag(app\modules\core\models\ContentBlock::className()),
368
        ];
369
        $content_key = 'templateChunkRender' . $key;
370
        if (null !== $model) {
371
            $content_key .= $model->id;
372
            $tags[] = ActiveRecordHelper::getObjectTag(get_class($model), $model->id);
373
        }
374
        $dependency = new TagDependency(['tags' => $tags]);
375
        if (false === empty($params)) {
376
            $rawChunk = self::compileChunk($rawChunk, $params, $key, $content_key, $dependency);
377
        }
378
        return self::compileContentString($rawChunk, $content_key, $dependency);
379
    }
380
381
    private static function renderProducts($chunkData, &$dependency)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
Unused Code introduced by
The parameter $dependency 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...
382
    {
383
        $params = [
384
            'itemView' => Yii::$app->getModule('shop')->itemView,
385
            'type' => 'show',
386
            'object' => 'product',
387
            'where' => [],
388
            'limit' => 0,
389
            'listView' => Yii::$app->getModule('shop')->listView,
390
        ];
391
        switch ($chunkData['key']) {
392
            case 'product':
393
                if (ArrayHelper::keyExists('sku', $chunkData)) {
394
                    $params['where'] = ['sku' => $chunkData['sku']];
395
                }
396
                break;
397
            case 'productList':
398
                $params['type'] = 'list';
399
                break;
400
            default:
401
                $expression = '%(?P<objectName>[^#]+?)#(?P<objectId>[\d]+?)$%';
402
                if (preg_match($expression, $chunkData['key'], $matches)) {
403
                    $params['where']['id'] = $matches['objectId'];
404
                }
405
                break;
406
        }
407
        switch ($params['object']) {
408
            case 'product':
409
                $query = Product::find();
410
                if (!empty($chunkData['categoryId'])) {
411
                    $query->leftJoin('{{%product_category}}', Product::tableName() . '.id = {{%product_category}}.object_model_id')
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 131 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...
412
                        ->andWhere(['{{%product_category}}.category_id' => $chunkData['categoryId']]);
413
                }
414
                if (!empty($chunkData['property'])) {
415
                    $expression = '%(?P<propertyKey>[^:]+?):(?P<propertyValue>.+?)$%';
416
                    if (preg_match($expression, $chunkData['property'], $matches)) {
417
                        $property = Property::findOne(['key' => $matches['propertyKey']]);
418
                        if (!is_null($property)) {
419
                            /** @var Property $property */
420
                            if ($property->is_eav == 1) {
421
                                $query->leftJoin('{{%product_eav}}', Product::tableName() . '.id = {{%product_eav}}.object_model_id')
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 133 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...
422
                                    ->andWhere([
423
                                        '{{%product_eav}}.key' => $matches['propertyKey'],
424
                                        '{{%product_eav}}.value' => $matches['propertyValue']
425
                                    ]);
426
                            } elseif ($property->has_static_values == 1) {
427
                                $psv = PropertyStaticValues::findOne([
428
                                    'property_id' => $property->id,
429
                                    'value' => $matches['propertyValue']
430
                                ]);
431
                                if (!is_null($psv)) {
432
                                    $query->leftJoin('{{%object_static_values}}', Product::tableName() . '.id = {{%object_static_values}}.object_model_id')
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 155 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...
433
                                        ->andWhere([
434
                                            'object_id' =>3,
435
                                            '{{%object_static_values}}.property_static_value_id' => $psv->id,
436
                                        ]);
437
                                } else {
438
                                    return '';
439
                                }
440
                            }
441
                            /** @todo add column_stored */
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...
442
                        } else {
443
                            return '';
444
                        }
445
                    }
446
                }
447
                break;
448
            default:
449
                $query = Product::find();
450
                break;
451
        }
452
        $params = ArrayHelper::merge($params, array_intersect_key($chunkData, $params));
453
        if (!empty($params['where'])) {
454
            $query->andWhere($params['where']);
455
        }
456
        if (!empty($params['limit'])) {
457
            $query->limit($params['limit']);
458
        }
459
460
        if ($params['type'] === 'list') {
461
            $view = $params['listView'];
462
            switch ($params['object']) {
463
                case 'product':
464
                    $viewParams = ['products' => $query->all()];
465
                    break;
466
                default:
467
                    $viewParams = ['products' => $query->all()];
468
                    break;
469
            }
470
        } else {
471
            $view = $params['itemView'];
472
            $object = $query->one();
473
            if (is_null($object)) {
474
                return '';
475
            }
476
            switch ($params['object']) {
477 View Code Duplication
                case 'product':
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across 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...
478
                    $viewParams = ['product' => $object, 'url' => Url::to(
479
                        [
480
                            '@product',
481
                            'model' => $object,
482
                            'category_group_id' => $object->getMainCategory()->category_group_id,
483
                        ]
484
                    )];
485
                    break;
486 View Code Duplication
                default:
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across 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
                    $viewParams = ['product' => $object, 'url' => Url::to(
488
                        [
489
                            '@product',
490
                            'model' => $object,
491
                            'category_group_id' => $object->getMainCategory()->category_group_id,
492
                        ]
493
                    )];
494
                    break;
495
            }
496
        }
497
        return Yii::$app->view->render($view, $viewParams);
498
    }
499
}
500