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:
Complex classes like ContentBlockHelper often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use ContentBlockHelper, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 27 | class ContentBlockHelper |
||
| 28 | { |
||
| 29 | private static $chunksByKey = []; |
||
| 30 | |||
| 31 | /** |
||
| 32 | * Compiles content string by injecting chunks into content |
||
| 33 | * Preloads chunks which have preload = 1 |
||
| 34 | * |
||
| 35 | * @param string $content Original content with chunk calls |
||
| 36 | * @param string $content_key Key for caching compiled content version |
||
| 37 | * @param yii\caching\Dependency $dependency Cache dependency |
||
| 38 | * @return string Compiled content with injected chunks |
||
| 39 | */ |
||
| 40 | public static function compileContentString($content, $content_key, $dependency) |
||
| 41 | { |
||
| 42 | self::preloadChunks(); |
||
| 43 | $output = self::processData($content, $content_key, $dependency); |
||
| 44 | $output = self::processData($output, $content_key, $dependency, '', false); |
||
| 45 | return $output; |
||
| 46 | } |
||
| 47 | |||
| 48 | /** |
||
| 49 | * Finding chunk calls with regexp |
||
| 50 | * Iterate matches |
||
| 51 | * While iterating: |
||
| 52 | * Extracts single chunk data with sanitizeChunk() method |
||
| 53 | * Fetches chunk by key using fetchChunkByKey(), who returns chunk value by key from static array if exists, otherwise from db |
||
|
|
|||
| 54 | * Compiles single chunk using compileChunk() method |
||
| 55 | * Replaces single chunk call with compiled chunk data in the model content |
||
| 56 | * |
||
| 57 | * @param string $content_key Key for caching compiled content version |
||
| 58 | * @param yii\caching\Dependency $dependency Cache dependency |
||
| 59 | * @param bool $preprocess flag to separate rendering non cacheable chunks such as Form |
||
| 60 | * @param string $content |
||
| 61 | * @param string $chunk_key ContentBlock key string to prevent endless recursion |
||
| 62 | * @return string |
||
| 63 | */ |
||
| 64 | private static function processData($content, $content_key, $dependency, $chunk_key = '', $preprocess = true) |
||
| 65 | { |
||
| 66 | $matches = []; |
||
| 67 | $replacement = ''; |
||
| 68 | preg_match_all('%\[\[([^\]\[]+)\]\]%ui', $content, $matches); |
||
| 69 | if (!empty($matches[0])) { |
||
| 70 | foreach ($matches[0] as $k => $rawChunk) { |
||
| 71 | $chunkData = self::sanitizeChunk($rawChunk); |
||
| 72 | if ($chunkData['key'] == $chunk_key) { |
||
| 73 | $content = str_replace($matches[0][$k], '', $content); |
||
| 74 | continue; |
||
| 75 | } |
||
| 76 | $cacheKey = $content_key . $chunkData['key'] . serialize($chunkData); |
||
| 77 | switch ($chunkData['token']) { |
||
| 78 | case '$': |
||
| 79 | if ($preprocess === false) break; |
||
| 80 | $chunk = self::fetchChunkByKey($chunkData['key']); |
||
| 81 | $replacement = Yii::$app->cache->get($cacheKey); |
||
| 82 | if ($replacement === false) { |
||
| 83 | $replacement = static::compileChunk($chunk, $chunkData, $chunkData['key'], $content_key, $dependency); |
||
| 84 | Yii::$app->cache->set( |
||
| 85 | $cacheKey, |
||
| 86 | $replacement, |
||
| 87 | 84600, |
||
| 88 | $dependency |
||
| 89 | ); |
||
| 90 | } |
||
| 91 | break; |
||
| 92 | case '%': |
||
| 93 | if ($preprocess === true) { |
||
| 94 | $replacement = $rawChunk; |
||
| 95 | break; |
||
| 96 | } |
||
| 97 | $replacement = static::replaceForms($chunkData); |
||
| 98 | break; |
||
| 99 | View Code Duplication | case '~' : |
|
| 100 | if ($preprocess === false) break; |
||
| 101 | $replacement = Yii::$app->cache->get($cacheKey); |
||
| 102 | if ($replacement === false) { |
||
| 103 | $replacement = static::renderUrl($chunkData, $dependency); |
||
| 104 | Yii::$app->cache->set( |
||
| 105 | $cacheKey, |
||
| 106 | $replacement, |
||
| 107 | 84600, |
||
| 108 | $dependency |
||
| 109 | ); |
||
| 110 | } |
||
| 111 | break; |
||
| 112 | View Code Duplication | case '*': |
|
| 113 | if ($preprocess === false) { |
||
| 114 | break; |
||
| 115 | } |
||
| 116 | $replacement = Yii::$app->cache->get($cacheKey); |
||
| 117 | if ($replacement === false) { |
||
| 118 | $replacement = static::renderProducts($chunkData, $dependency); |
||
| 119 | Yii::$app->cache->set( |
||
| 120 | $cacheKey, |
||
| 121 | $replacement, |
||
| 122 | 84600, |
||
| 123 | $dependency |
||
| 124 | ); |
||
| 125 | } |
||
| 126 | break; |
||
| 127 | } |
||
| 128 | $content = str_replace($matches[0][$k], $replacement, $content); |
||
| 129 | } |
||
| 130 | } |
||
| 131 | return $content; |
||
| 132 | } |
||
| 133 | |||
| 134 | /** |
||
| 135 | * @param array $chunkData |
||
| 136 | * @return mixed |
||
| 137 | */ |
||
| 138 | private static function replaceForms($chunkData) |
||
| 139 | { |
||
| 140 | $regexp = '/^(?P<formId>\d+)(#(?P<id>[\w\d\-_]+))?(;(?P<isModal>isModal))?$/Usi'; |
||
| 141 | return preg_replace_callback( |
||
| 142 | $regexp, |
||
| 143 | function ($matches) { |
||
| 144 | if (isset($matches['formId'])) { |
||
| 145 | $params = ['formId' => intval($matches['formId'])]; |
||
| 146 | if (isset($matches['id'])) { |
||
| 147 | $params['id'] = $matches['id']; |
||
| 148 | } |
||
| 149 | if (isset($matches['isModal'])) { |
||
| 150 | $params['isModal'] = true; |
||
| 151 | } |
||
| 152 | return app\widgets\form\Form::widget($params); |
||
| 153 | } |
||
| 154 | return ''; |
||
| 155 | }, |
||
| 156 | $chunkData['key'] |
||
| 157 | ); |
||
| 158 | } |
||
| 159 | |||
| 160 | /** |
||
| 161 | * renders url according to given data |
||
| 162 | * @param $chunkData |
||
| 163 | * @param TagDependency $dependency |
||
| 164 | * @return string |
||
| 165 | */ |
||
| 166 | private static function renderUrl($chunkData, &$dependency) |
||
| 167 | { |
||
| 168 | $expression = '%(?P<objectName>[^#]+?)#(?P<objectId>[\d]+?)$%'; |
||
| 169 | $output = ''; |
||
| 170 | preg_match($expression, $chunkData['key'], $m); |
||
| 171 | if (true === isset($m['objectName'], $m['objectId'])) { |
||
| 172 | $id = (int)$m['objectId']; |
||
| 173 | switch (strtolower($m['objectName'])) { |
||
| 174 | View Code Duplication | case "page" : |
|
| 175 | if (null !== $model = Page::findById($id)) { |
||
| 176 | $dependency->tags [] = ActiveRecordHelper::getCommonTag(Page::className()); |
||
| 177 | $dependency->tags [] = $model->objectTag(); |
||
| 178 | $output = Url::to(['@article', 'id' => $id]); |
||
| 179 | } |
||
| 180 | break; |
||
| 181 | View Code Duplication | case "category" : |
|
| 182 | if (null !== $model = Category::findById($id)) { |
||
| 183 | $dependency->tags [] = ActiveRecordHelper::getCommonTag(Category::className()); |
||
| 184 | $dependency->tags [] = $model->objectTag(); |
||
| 185 | $output = Url::to(['@category', 'last_category_id' => $id]); |
||
| 186 | } |
||
| 187 | break; |
||
| 188 | View Code Duplication | case "product" : |
|
| 189 | if (null !== $model = app\modules\shop\models\Product::findById($id)) { |
||
| 190 | $dependency->tags [] = ActiveRecordHelper::getCommonTag(Product::className()); |
||
| 191 | $dependency->tags [] = $model->objectTag(); |
||
| 192 | $output = Url::to(['@product', 'model' => $model]); |
||
| 193 | } |
||
| 194 | break; |
||
| 195 | } |
||
| 196 | } |
||
| 197 | return $output; |
||
| 198 | } |
||
| 199 | |||
| 200 | /** |
||
| 201 | * Extracts chunk data from chunk call |
||
| 202 | * uses regexp to extract param data from placeholder |
||
| 203 | * [[$chunk <paramName>='<escapedValue>'|'<escapedDefault>' <paramName>=<unescapedValue>|<unescapedDefault>]] |
||
| 204 | * iterate matches. |
||
| 205 | * While iterating converts escapedValue and escapedDefault into string, unescapedValue and unescapedDefault - into float |
||
| 206 | * Returns chunk data array like: |
||
| 207 | * [ |
||
| 208 | * 'key' => 'chunkKey', |
||
| 209 | * 'firstParam'=> 'string value', |
||
| 210 | * 'firstParam-default'=> 'default string value', |
||
| 211 | * 'secondParam'=> float value, |
||
| 212 | * 'secondParam-default'=> default float value, |
||
| 213 | * ] |
||
| 214 | * |
||
| 215 | * @param string $rawChunk |
||
| 216 | * @return array |
||
| 217 | */ |
||
| 218 | private static function sanitizeChunk($rawChunk) |
||
| 219 | { |
||
| 220 | $chunk = []; |
||
| 221 | preg_match('%(?P<chunkToken>[^\w\[]?)([^\s\]\[]+)[\s\]]%', $rawChunk, $keyMatches); |
||
| 222 | $chunk['token'] = $keyMatches['chunkToken']; |
||
| 223 | $chunk['key'] = $keyMatches[2]; |
||
| 224 | $expression = "#\s*(?P<paramName>[\\w\\d]*)=(('(?P<escapedValue>.*[^\\\\])')|(?P<unescapedValue>.*))(\\|(('(?P<escapedDefault>.*[^\\\\])')|(?P<unescapedDefault>.*)))?[\\]\\s]#uUi"; |
||
| 225 | preg_match_all($expression, $rawChunk, $matches); |
||
| 226 | foreach ($matches['paramName'] as $key => $paramName) { |
||
| 227 | if (!empty($matches['escapedValue'][$key])) { |
||
| 228 | $chunk[$paramName] = strval($matches['escapedValue'][$key]); |
||
| 229 | } |
||
| 230 | if (!empty($matches['unescapedValue'][$key])) { |
||
| 231 | $chunk[$paramName] = floatval($matches['unescapedValue'][$key]); |
||
| 232 | } |
||
| 233 | View Code Duplication | if (!empty($matches['escapedDefault'][$key])) { |
|
| 234 | $chunk[$paramName . '-default'] = strval($matches['escapedDefault'][$key]); |
||
| 235 | } |
||
| 236 | View Code Duplication | if (!empty($matches['unescapedDefault'][$key])) { |
|
| 237 | $chunk[$paramName . '-default'] = floatval($matches['unescapedDefault'][$key]); |
||
| 238 | } |
||
| 239 | } |
||
| 240 | return $chunk; |
||
| 241 | } |
||
| 242 | |||
| 243 | /** |
||
| 244 | * Compiles single chunk |
||
| 245 | * uses regexp to find placeholders and extract it's data from chunk value field |
||
| 246 | * [[<token><paramName>:<format><params>]] |
||
| 247 | * token switch is for future functionality increase |
||
| 248 | * now method only recognizes + token and replaces following param with according $arguments array data |
||
| 249 | * applies formatter according previously defined param values type if needed |
||
| 250 | * if param name from placeholder was not found in arguments array, placeholder in the compiled chunk will be replaced with empty string |
||
| 251 | * returns compiled chunk |
||
| 252 | * |
||
| 253 | * @param string $content_key Key for caching compiled content version |
||
| 254 | * @param yii\caching\Dependency $dependency Cache dependency |
||
| 255 | * @param string $chunk ContentBlock instance |
||
| 256 | * @param array $arguments Arguments for this chunk from original content |
||
| 257 | * @param string $key ContentBlock key string to prevent endless recursion |
||
| 258 | * @return string Result string ready for replacing |
||
| 259 | */ |
||
| 260 | private static function compileChunk($chunk, $arguments, $key, $content_key, $dependency) |
||
| 261 | { |
||
| 262 | $matches = []; |
||
| 263 | preg_match_all('%\[\[(?P<token>[\+\*])(?P<paramName>[^\s\:\]]+)\:?(?P<format>[^\,\]]+)?\,?(?P<params>[^\]]+)?\]\]%ui', $chunk, $matches); |
||
| 264 | foreach ($matches[0] as $k => $rawParam) { |
||
| 265 | $token = $matches['token'][$k]; |
||
| 266 | $paramName = trim($matches['paramName'][$k]); |
||
| 267 | $format = trim($matches['format'][$k]); |
||
| 268 | $params = preg_replace('%[\s]%', '', $matches['params'][$k]); |
||
| 269 | $params = explode(',', $params); |
||
| 270 | switch ($token) { |
||
| 271 | case '+': |
||
| 272 | if (array_key_exists($paramName, $arguments)) { |
||
| 273 | $replacement = static::applyFormatter($arguments[$paramName], $format, $params); |
||
| 274 | $chunk = str_replace($matches[0][$k], $replacement, $chunk); |
||
| 275 | } else if (array_key_exists($paramName . '-default', $arguments)) { |
||
| 276 | $replacement = static::applyFormatter($arguments[$paramName . '-default'], $format, $params); |
||
| 277 | $chunk = str_replace($matches[0][$k], $replacement, $chunk); |
||
| 278 | } else { |
||
| 279 | $chunk = str_replace($matches[0][$k], '', $chunk); |
||
| 280 | } |
||
| 281 | break; |
||
| 282 | default: |
||
| 283 | $chunk = str_replace($matches[0][$k], '', $chunk); |
||
| 284 | } |
||
| 285 | } |
||
| 286 | return self::processData($chunk, $content_key, $dependency, $key); |
||
| 287 | } |
||
| 288 | |||
| 289 | /** |
||
| 290 | * Find formatter declarations in chunk placeholders. if find trying to apply |
||
| 291 | * yii\i18n\Formatter formats see yii\i18n\Formatter for details |
||
| 292 | * |
||
| 293 | * @param string $value single placeholder declaration from chunk |
||
| 294 | * @param string $format |
||
| 295 | * @param array $params |
||
| 296 | * @return string|array |
||
| 297 | */ |
||
| 298 | private static function applyFormatter($value, $format, $params) |
||
| 299 | { |
||
| 300 | if (false === method_exists(Yii::$app->formatter, $format) || empty($format)) { |
||
| 301 | return $value; |
||
| 302 | } |
||
| 303 | array_unshift($params, $value); |
||
| 304 | try { |
||
| 305 | $formattedValue = call_user_func_array([Yii::$app->formatter, $format], $params); |
||
| 306 | } catch (\Exception $e) { |
||
| 307 | $formattedValue = $value; |
||
| 308 | } |
||
| 309 | return $formattedValue; |
||
| 310 | } |
||
| 311 | |||
| 312 | /** |
||
| 313 | * Fetches single chunk by key from static var |
||
| 314 | * if is no there - get it from db and push to static array |
||
| 315 | * |
||
| 316 | * @param $key string Chunk key field |
||
| 317 | * @return string Chunk value field |
||
| 318 | */ |
||
| 319 | private static function fetchChunkByKey($key) |
||
| 320 | { |
||
| 321 | if (!array_key_exists($key, static::$chunksByKey)) { |
||
| 322 | $dependency = new TagDependency([ |
||
| 323 | 'tags' => [ |
||
| 324 | ActiveRecordHelper::getCommonTag(ContentBlock::className()), |
||
| 325 | ] |
||
| 326 | ]); |
||
| 327 | static::$chunksByKey[$key] = ContentBlock::getDb()->cache(function ($db) use ($key) { |
||
| 328 | $chunk = ContentBlock::find() |
||
| 329 | ->where(['key' => $key]) |
||
| 330 | ->asArray() |
||
| 331 | ->one(); |
||
| 332 | return static::$chunksByKey[$key] = $chunk['value']; |
||
| 333 | }, 86400, $dependency); |
||
| 334 | } |
||
| 335 | return static::$chunksByKey[$key]; |
||
| 336 | } |
||
| 337 | |||
| 338 | /** |
||
| 339 | * preloads chunks with option preload = 1 |
||
| 340 | * and push it to static array |
||
| 341 | * |
||
| 342 | * @return array|void |
||
| 343 | */ |
||
| 344 | private static function preloadChunks() |
||
| 345 | { |
||
| 346 | if (is_null(static::$chunksByKey)) { |
||
| 347 | $dependency = new TagDependency([ |
||
| 348 | 'tags' => [ |
||
| 349 | ActiveRecordHelper::getCommonTag(ContentBlock::className()), |
||
| 350 | ] |
||
| 351 | ]); |
||
| 352 | static::$chunksByKey = ContentBlock::getDb()->cache(function ($db) { |
||
| 353 | $chunks = ContentBlock::find() |
||
| 354 | ->where(['preload' => 1]) |
||
| 355 | ->asArray() |
||
| 356 | ->all(); |
||
| 357 | return ArrayHelper::map($chunks, 'key', 'value'); |
||
| 358 | }, 86400, $dependency); |
||
| 359 | } |
||
| 360 | return static::$chunksByKey; |
||
| 361 | } |
||
| 362 | |||
| 363 | /** |
||
| 364 | * renders chunks in template files |
||
| 365 | * @param string $key ContentBlock key |
||
| 366 | * @param array $params . Array of params to be replaced while render |
||
| 367 | * @param yii\base\Model $model . Caller model instance to use in caching |
||
| 368 | * @return mixed |
||
| 369 | */ |
||
| 370 | public static function getChunk($key, $params = [], yii\base\Model $model = null) |
||
| 371 | { |
||
| 372 | if (null === $rawChunk = self::fetchChunkByKey($key)) { |
||
| 373 | return ''; |
||
| 374 | } |
||
| 375 | $tags = [ |
||
| 376 | ActiveRecordHelper::getCommonTag(app\modules\core\models\ContentBlock::className()), |
||
| 377 | ]; |
||
| 378 | $content_key = 'templateChunkRender' . $key; |
||
| 379 | if (null !== $model) { |
||
| 380 | $content_key .= $model->id; |
||
| 381 | $tags[] = ActiveRecordHelper::getObjectTag(get_class($model), $model->id); |
||
| 382 | } |
||
| 383 | $dependency = new TagDependency(['tags' => $tags]); |
||
| 384 | if (false === empty($params)) { |
||
| 385 | $rawChunk = self::compileChunk($rawChunk, $params, $key, $content_key, $dependency); |
||
| 386 | } |
||
| 387 | return self::compileContentString($rawChunk, $content_key, $dependency); |
||
| 388 | } |
||
| 389 | |||
| 390 | /** |
||
| 391 | * renders product item and list. |
||
| 392 | * possible can render all objects, but need for few logic change |
||
| 393 | * @param array $chunkData params for select and render |
||
| 394 | * @param TagDependency $dependency |
||
| 395 | * @return mixed |
||
| 396 | */ |
||
| 397 | private static function renderProducts($chunkData, &$dependency) |
||
| 550 | } |
||
| 551 |
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.