Total Complexity | 104 |
Total Lines | 518 |
Duplicated Lines | 0 % |
Changes | 10 | ||
Bugs | 4 | Features | 0 |
Complex classes like DLTemplate 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.
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 DLTemplate, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
9 | class DLTemplate |
||
10 | { |
||
11 | /** |
||
12 | * Объект DocumentParser - основной класс MODX |
||
13 | * @var DocumentParser $modx |
||
14 | * @access protected |
||
15 | */ |
||
16 | protected $modx = null; |
||
17 | |||
18 | /** |
||
19 | * @var DLTemplate cached reference to singleton instance |
||
20 | */ |
||
21 | protected static $instance; |
||
22 | |||
23 | protected $templatePath = 'assets/templates/'; |
||
24 | |||
25 | protected $templateExtension = 'html'; |
||
26 | |||
27 | /** |
||
28 | * @var null|Twig_Environment twig object |
||
29 | */ |
||
30 | protected $twig = null; |
||
31 | |||
32 | /** |
||
33 | * @var null|Jenssegers\Blade\Blade blade object |
||
34 | */ |
||
35 | protected $blade = null; |
||
36 | |||
37 | protected $twigEnabled = false; |
||
38 | |||
39 | protected $bladeEnabled = false; |
||
40 | |||
41 | protected $twigTemplateVars = array(); |
||
42 | |||
43 | public $phx = null; |
||
44 | |||
45 | /** |
||
46 | * gets the instance via lazy initialization (created on first usage) |
||
47 | * |
||
48 | * @return self |
||
49 | */ |
||
50 | public static function getInstance(DocumentParser $modx) |
||
58 | } |
||
59 | |||
60 | /** |
||
61 | * is not allowed to call from outside: private! |
||
62 | * |
||
63 | */ |
||
64 | private function __construct(DocumentParser $modx) |
||
67 | } |
||
68 | |||
69 | /** |
||
70 | * prevent the instance from being cloned |
||
71 | * |
||
72 | * @return void |
||
73 | */ |
||
74 | private function __clone() |
||
75 | { |
||
76 | } |
||
77 | |||
78 | /** |
||
79 | * prevent from being unserialized |
||
80 | * |
||
81 | * @return void |
||
82 | */ |
||
83 | private function __wakeup() |
||
84 | { |
||
85 | } |
||
86 | |||
87 | /** |
||
88 | * Задает относительный путь к папке с шаблонами |
||
89 | * |
||
90 | * @param $path |
||
91 | * @param bool $supRoot |
||
92 | * @return $this |
||
93 | */ |
||
94 | public function setTemplatePath($path, $supRoot = false) |
||
95 | { |
||
96 | $path = trim($path); |
||
97 | if ($supRoot === false) { |
||
98 | $path = preg_replace(array( |
||
99 | '/\.*[\/|\\\]/i', |
||
100 | '/[\/|\\\]+/i' |
||
101 | ), array('/', '/'), $path); |
||
102 | } |
||
103 | |||
104 | if (!empty($path)) { |
||
105 | $this->templatePath = $path; |
||
106 | } |
||
107 | |||
108 | return $this; |
||
109 | } |
||
110 | |||
111 | /** |
||
112 | * Задает расширение файла с шаблоном |
||
113 | * |
||
114 | * @param $ext |
||
115 | * @return $this |
||
116 | */ |
||
117 | public function setTemplateExtension($ext) |
||
118 | { |
||
119 | $ext = preg_replace(array( |
||
120 | '/\.*[\/|\\\]/i', |
||
121 | '/[\/|\\\]+/i' |
||
122 | ), array('/', '/'), trim($ext, ". \t\n\r\0\x0B")); |
||
123 | |||
124 | if (!empty($ext)) { |
||
125 | $this->templateExtension = $ext; |
||
126 | } |
||
127 | |||
128 | return $this; |
||
129 | } |
||
130 | |||
131 | /** |
||
132 | * Additional data for twig templates |
||
133 | * |
||
134 | * @param array $data |
||
135 | * @return $this |
||
136 | */ |
||
137 | public function setTwigTemplateVars($data = array()) |
||
138 | { |
||
139 | if (is_array($data)) { |
||
140 | $this->twigTemplateVars = $data; |
||
141 | } |
||
142 | |||
143 | return $this; |
||
144 | } |
||
145 | |||
146 | /** |
||
147 | * Сохранение данных в массив плейсхолдеров |
||
148 | * |
||
149 | * @param mixed $data данные |
||
150 | * @param int $set устанавливать ли глобальнй плейсхолдер MODX |
||
151 | * @param string $key ключ локального плейсхолдера |
||
152 | * @param string $prefix префикс для ключей массива |
||
153 | * @return string |
||
154 | */ |
||
155 | public function toPlaceholders($data, $set = 0, $key = 'contentPlaceholder', $prefix = '') |
||
156 | { |
||
157 | $out = ''; |
||
158 | if ($set != 0) { |
||
159 | $this->modx->toPlaceholder($key, $data, $prefix); |
||
160 | } else { |
||
161 | $out = $data; |
||
162 | } |
||
163 | |||
164 | return $out; |
||
165 | } |
||
166 | |||
167 | /** |
||
168 | * refactor $modx->getChunk(); |
||
169 | * |
||
170 | * @param string $name Template: chunk name || @CODE: template || @FILE: file with template |
||
171 | * @return string html template with placeholders without data |
||
172 | */ |
||
173 | public function getChunk($name) |
||
174 | { |
||
175 | $tpl = ''; |
||
176 | $this->twigEnabled = (0 === strpos($name, '@T_')); |
||
177 | $this->bladeEnabled = (0 === strpos($name, '@B_')); |
||
178 | if ($name != '' && !isset($this->modx->chunkCache[$name])) { |
||
179 | $mode = (preg_match( |
||
180 | '/^((@[A-Z_]+)[:]{0,1})(.*)/Asu', |
||
181 | trim($name), |
||
182 | $tmp |
||
183 | ) && isset($tmp[2], $tmp[3])) ? $tmp[2] : false; |
||
184 | $subTmp = (isset($tmp[3])) ? trim($tmp[3]) : null; |
||
185 | if ($this->twigEnabled) { |
||
186 | $mode = '@' . substr($mode, 3); |
||
187 | } elseif ($this->bladeEnabled) { |
||
188 | $mode = '@' . substr($mode, 3); |
||
189 | } |
||
190 | switch ($mode) { |
||
191 | case '@FILE': |
||
192 | if ($subTmp != '') { |
||
193 | $real = realpath(MODX_BASE_PATH . $this->templatePath); |
||
194 | $path = realpath(MODX_BASE_PATH . $this->templatePath . preg_replace(array( |
||
195 | '/\.*[\/|\\\]/i', |
||
196 | '/[\/|\\\]+/i' |
||
197 | ), array('/', '/'), $subTmp) . '.' . $this->templateExtension); |
||
198 | if (basename($path, '.' . $this->templateExtension) !== '' && |
||
199 | 0 === strpos($path, $real) && |
||
200 | file_exists($path) |
||
201 | ) { |
||
202 | $tpl = file_get_contents($path); |
||
203 | } |
||
204 | } |
||
205 | break; |
||
206 | case '@CHUNK': |
||
207 | if ($subTmp != '') { |
||
208 | $tpl = $this->modx->getChunk($subTmp); |
||
209 | } |
||
210 | break; |
||
211 | case '@INLINE': |
||
212 | case '@TPL': |
||
213 | case '@CODE': |
||
214 | $tpl = $tmp[3]; //without trim |
||
215 | break; |
||
216 | case '@DOCUMENT': |
||
217 | case '@DOC': |
||
218 | switch (true) { |
||
219 | case ((int)$subTmp > 0): |
||
220 | $tpl = $this->modx->getPageInfo((int)$subTmp, 0, "content"); |
||
221 | $tpl = isset($tpl['content']) ? $tpl['content'] : ''; |
||
222 | break; |
||
223 | case ((int)$subTmp == 0): |
||
224 | $tpl = $this->modx->documentObject['content']; |
||
225 | break; |
||
226 | } |
||
227 | break; |
||
228 | case '@PLH': |
||
229 | case '@PLACEHOLDER': |
||
230 | if ($subTmp != '') { |
||
231 | $tpl = $this->modx->getPlaceholder($subTmp); |
||
232 | } |
||
233 | break; |
||
234 | case '@CFG': |
||
235 | case '@CONFIG': |
||
236 | case '@OPTIONS': |
||
237 | if ($subTmp != '') { |
||
238 | $tpl = $this->modx->getConfig($subTmp); |
||
239 | } |
||
240 | break; |
||
241 | case '@SNIPPET': |
||
242 | if ($subTmp != '') { |
||
243 | $tpl = $this->modx->runSnippet($subTmp, $this->modx->event->params); |
||
244 | } |
||
245 | break; |
||
246 | case '@RENDERPAGE': |
||
247 | $tpl = $this->renderDoc($subTmp, false); |
||
248 | break; |
||
249 | case '@LOADPAGE': |
||
250 | $tpl = $this->renderDoc($subTmp, true); |
||
251 | break; |
||
252 | case '@TEMPLATE': |
||
253 | $tpl = $this->getTemplate($subTmp); |
||
254 | break; |
||
255 | default: |
||
256 | $tpl = $this->modx->getChunk($name); |
||
257 | } |
||
258 | $this->modx->chunkCache[$name] = $tpl; |
||
259 | } else { |
||
260 | if ($name != '') { |
||
261 | $tpl = $this->modx->getChunk($name); |
||
262 | } |
||
263 | } |
||
264 | |||
265 | return $tpl; |
||
266 | } |
||
267 | |||
268 | /** |
||
269 | * Рендер документа с подстановкой плейсхолдеров и выполнением сниппетов |
||
270 | * |
||
271 | * @param int $id ID документа |
||
272 | * @param bool $events Во время рендера документа стоит ли вызывать события OnLoadWebDocument и OnLoadDocumentObject (внутри метода getDocumentObject). |
||
273 | * @param mixed $tpl Шаблон с которым необходимо отрендерить документ. Возможные значения: |
||
274 | * null - Использовать шаблон который назначен документу |
||
275 | * int(0-n) - Получить шаблон из базы данных с указанным ID и применить его к документу |
||
276 | * string - Применить шаблон указанный в строке к документу |
||
277 | * @return string |
||
278 | * |
||
279 | * Событие OnLoadWebDocument дополнительно передает параметры: |
||
280 | * - с источиком от куда произошел вызов события |
||
281 | * - оригинальный экземпляр класса DocumentParser |
||
282 | */ |
||
283 | public function renderDoc($id, $events = false, $tpl = null) |
||
284 | { |
||
285 | $id = (int)$id; |
||
286 | if ($id <= 0) { |
||
287 | return ''; |
||
288 | } |
||
289 | |||
290 | $m = clone $this->modx; //Чтобы была возможность вызывать события |
||
291 | $m->documentIdentifier = $id; |
||
292 | $m->documentObject = $m->getDocumentObject('id', (int)$id, $events ? 'prepareResponse' : null); |
||
293 | if ($m->documentObject['type'] == "reference") { |
||
294 | if (is_numeric($m->documentObject['content']) && $m->documentObject['content'] > 0) { |
||
295 | $m->documentObject['content'] = $this->renderDoc($m->documentObject['content'], $events); |
||
296 | } |
||
297 | } |
||
298 | switch (true) { |
||
299 | case is_integer($tpl): |
||
300 | $tpl = $this->getTemplate($tpl); |
||
301 | break; |
||
302 | case is_string($tpl): |
||
303 | break; |
||
304 | case is_null($tpl): |
||
305 | default: |
||
306 | $tpl = $this->getTemplate($m->documentObject['template']); |
||
307 | } |
||
308 | $m->documentContent = $tpl; |
||
309 | if ($events) { |
||
310 | $m->invokeEvent("OnLoadWebDocument", array( |
||
311 | 'source' => 'DLTemplate', |
||
312 | 'mainModx' => $this->modx, |
||
313 | )); |
||
314 | } |
||
315 | |||
316 | return $this->parseDocumentSource($m->documentContent, $m); |
||
317 | } |
||
318 | |||
319 | /** |
||
320 | * Получить содержимое шаблона с определенным номером |
||
321 | * @param int $id Номер шаблона |
||
322 | * @return string HTML код шаблона |
||
323 | */ |
||
324 | public function getTemplate($id) |
||
325 | { |
||
326 | $tpl = null; |
||
327 | $id = (int)$id; |
||
328 | if ($id > 0) { |
||
329 | $tpl = $this->modx->getDatabase()->getValue("SELECT `content` FROM {$this->modx->getDatabase()->getFullTableName("site_templates")} WHERE `id` = {$id}"); |
||
330 | } |
||
331 | if (is_null($tpl)) { |
||
332 | $tpl = '[*content*]'; |
||
333 | } |
||
334 | |||
335 | return $tpl; |
||
336 | } |
||
337 | |||
338 | /** |
||
339 | * refactor $modx->parseChunk(); |
||
340 | * |
||
341 | * @param string $name Template: chunk name || @CODE: template || @FILE: file with template |
||
342 | * @param array $data paceholder |
||
343 | * @param bool $parseDocumentSource render html template via DocumentParser::parseDocumentSource() |
||
344 | * @return string html template with data without placeholders |
||
345 | */ |
||
346 | public function parseChunk($name, $data = array(), $parseDocumentSource = false, $disablePHx = false) |
||
347 | { |
||
348 | $out = $this->getChunk($name); |
||
349 | switch (true) { |
||
350 | case $this->twigEnabled && $out !== '' && ($twig = $this->getTwig($name, $out)): |
||
351 | $plh = $this->twigTemplateVars; |
||
352 | $plh['data'] = $data; |
||
353 | $plh['modx'] = $this->modx; |
||
354 | $out = $twig->render(md5($name), $plh); |
||
355 | break; |
||
356 | case $this->bladeEnabled && $out !== '' && ($blade = $this->getBlade($name, $out)): |
||
357 | $out = $blade->with($data); |
||
358 | break; |
||
359 | case is_array($data) && ($out != ''): |
||
360 | if (preg_match("/\[\+[A-Z0-9\.\_\-]+\+\]/is", $out)) { |
||
361 | $item = $this->renameKeyArr($data, '[', ']', '+'); |
||
362 | $out = str_replace(array_keys($item), array_values($item), $out); |
||
363 | } |
||
364 | if (!$disablePHx && preg_match("/:([^:=]+)(?:=`(.*?)`(?=:[^:=]+|$))?/is", $out)) { |
||
365 | if (is_null($this->phx) || !($this->phx instanceof DLphx)) { |
||
366 | $this->phx = $this->createPHx(0, 1000); |
||
367 | } |
||
368 | $this->phx->placeholders = array(); |
||
369 | $this->setPHxPlaceholders($data); |
||
370 | $out = $this->phx->Parse($out); |
||
371 | $out = $this->cleanPHx($out); |
||
372 | } |
||
373 | break; |
||
374 | } |
||
375 | if ($parseDocumentSource) { |
||
376 | $out = $this->parseDocumentSource($out); |
||
377 | } |
||
378 | |||
379 | return $out; |
||
380 | } |
||
381 | |||
382 | /** |
||
383 | * |
||
384 | * @param string|array $value |
||
385 | * @param string $key |
||
386 | * @param string $path |
||
387 | */ |
||
388 | public function setPHxPlaceholders($value = '', $key = '', $path = '') |
||
389 | { |
||
390 | $keypath = !empty($path) ? $path . "." . $key : $key; |
||
391 | $this->phx->curPass = 0; |
||
392 | if (is_array($value)) { |
||
393 | foreach ($value as $subkey => $subval) { |
||
394 | $this->setPHxPlaceholders($subval, $subkey, $keypath); |
||
395 | } |
||
396 | } else { |
||
397 | $this->phx->setPHxVariable($keypath, $value); |
||
398 | } |
||
399 | } |
||
400 | |||
401 | /** |
||
402 | * Return clone of twig |
||
403 | * |
||
404 | * @param string $name |
||
405 | * @param string $tpl |
||
406 | * @return null |
||
407 | */ |
||
408 | protected function getTwig($name, $tpl) |
||
409 | { |
||
410 | if (is_null($this->twig) && isset($this->modx->twig)) { |
||
411 | $twig = clone $this->modx->twig; |
||
412 | $this->twig = $twig; |
||
413 | } else { |
||
414 | $twig = $this->twig; |
||
415 | } |
||
416 | if ($twig && class_exists('Twig_Loader_Array')) { |
||
417 | $twig->getLoader()->addLoader( |
||
418 | new Twig_Loader_Array(array( |
||
419 | md5($name) => $tpl |
||
420 | )) |
||
421 | ); |
||
422 | } |
||
423 | |||
424 | return $twig; |
||
425 | } |
||
426 | |||
427 | /** |
||
428 | * Return clone of blade |
||
429 | * |
||
430 | * @param string $name |
||
431 | * @param string $tpl |
||
432 | * @return null |
||
433 | */ |
||
434 | protected function getBlade($name, $tpl) |
||
435 | { |
||
436 | if ($this->blade === null && isset($this->modx->blade)) { |
||
437 | $blade = clone $this->modx->blade; |
||
438 | $this->blade = $blade; |
||
439 | } else { |
||
440 | $blade = $this->blade; |
||
441 | } |
||
442 | |||
443 | $cache = md5($name). '-'. sha1($tpl); |
||
444 | $path = $blade->viewPaths . '/~cache/' . $cache . '.blade.php'; |
||
445 | if (! file_exists($path)) { |
||
446 | file_put_contents($path, $tpl); |
||
447 | } |
||
448 | |||
449 | return $blade->make('~cache/' . $cache, [ |
||
450 | 'modx' => $this->modx |
||
451 | ]); |
||
452 | } |
||
453 | |||
454 | /** |
||
455 | * |
||
456 | * @param string $string |
||
457 | * @return string |
||
458 | */ |
||
459 | public function cleanPHx($string) |
||
460 | { |
||
461 | preg_match_all('~\[(\+|\*|\()([^:\+\[\]]+)([^\[\]]*?)(\1|\))\]~s', $string, $matches); |
||
462 | if ($matches[0]) { |
||
463 | $string = str_replace($matches[0], '', $string); |
||
464 | } |
||
465 | |||
466 | return $string; |
||
467 | } |
||
468 | |||
469 | /** |
||
470 | * @param int $debug |
||
471 | * @param int $maxpass |
||
472 | * @return DLphx |
||
473 | */ |
||
474 | public function createPHx($debug = 0, $maxpass = 50) |
||
475 | { |
||
476 | if (!class_exists('DLphx')) { |
||
477 | include_once(__DIR__ . '/DLphx.class.php'); |
||
478 | } |
||
479 | |||
480 | return new DLphx($this->modx, $debug, $maxpass); |
||
481 | } |
||
482 | |||
483 | /** |
||
484 | * Переменовывание элементов массива |
||
485 | * |
||
486 | * @param array $data массив с данными |
||
487 | * @param string $prefix префикс ключей |
||
488 | * @param string $suffix суффикс ключей |
||
489 | * @param string $sep разделитель суффиксов, префиксов и ключей массива |
||
490 | * @return array массив с переименованными ключами |
||
491 | */ |
||
492 | public function renameKeyArr($data, $prefix = '', $suffix = '', $sep = '.') |
||
493 | { |
||
494 | return APIhelpers::renameKeyArr($data, $prefix, $suffix, $sep); |
||
495 | } |
||
496 | |||
497 | /** |
||
498 | * @param $out |
||
499 | * @param DocumentParser|null $modx |
||
500 | * @return mixed|string |
||
501 | */ |
||
502 | public function parseDocumentSource($out, $modx = null) |
||
527 | } |
||
528 | } |
||
529 |
The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g.
excluded_paths: ["lib/*"]
, you can move it to the dependency path list as follows:For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths