DLTemplate::setPHxPlaceholders()   A
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
eloc 7
c 0
b 0
f 0
dl 0
loc 10
ccs 0
cts 6
cp 0
rs 10
cc 4
nc 6
nop 3
crap 20
1
<?php
2
if (!class_exists('\\DLTemplate')) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after NOT operator; 0 found
Loading history...
3 1
    include_once(MODX_BASE_PATH . 'assets/lib/APIHelpers.class.php');
4
5
    /**
6
     * Class DLTemplate
7
     */
8
    class DLTemplate
9
    {
10
        /**
11
         * Объект DocumentParser - основной класс MODX
12
         * @var DocumentParser $modx
13
         * @access protected
14
         */
15
        protected $modx = null;
16
17
        /**
18
         * @var DLTemplate cached reference to singleton instance
19
         */
20
        protected static $instance;
21
22
        protected $templatePath = 'assets/templates/';
23
24
        protected $templateExtension = 'html';
25
26
        /**
27
         * @var null|Twig_Environment
0 ignored issues
show
Bug introduced by
The type Twig_Environment was not found. Maybe you did not declare it correctly or list all dependencies?

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:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
28
         */
29
        protected $twig;
30
        /*
31
         * @var Illuminate\View\Factory
0 ignored issues
show
Bug introduced by
The type Illuminate\View\Factory was not found. Maybe you did not declare it correctly or list all dependencies?

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:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
32
         */
33
        protected $blade;
34
35
        protected $twigEnabled = false;
36
        protected $bladeEnabled = false;
37
            
38
        protected $templateData = array();
39
40
        public $phx;
41
42
        /**
43 58
         * gets the instance via lazy initialization (created on first usage)
44
         *
45
         * @return self
46 58
         */
47 1
        public static function getInstance(DocumentParser $modx)
48 1
        {
49
50 58
            if (null === self::$instance) {
51
                self::$instance = new self($modx);
52
            }
53
54
            return self::$instance;
55
        }
56
57 1
        /**
58
         * is not allowed to call from outside: private!
59 1
         *
60 1
         */
61
        private function __construct(DocumentParser $modx)
62
        {
63
            $this->modx = $modx;
64
        }
65
66
        /**
67
         * prevent the instance from being cloned
68
         *
69
         * @return void
70
         */
71
        private function __clone()
72
        {
73
        }
74
75
        /**
76
         * prevent from being unserialized
77
         *
78
         * @return void
79
         */
80
        public function __wakeup()
81
        {
82
        }
83
84
        public function getTemplatePath()
85
        {
86
            return $this->templatePath;
87
        }
88
89
        /**
90
         * Задает относительный путь к папке с шаблонами
91
         *
92
         * @param string $path
93
         * @param bool $supRoot
94
         * @return $this
95
         */
96
        public function setTemplatePath($path, $supRoot = false)
97
        {
98
            $path = trim($path ?? '');
99
            if ($supRoot === false) {
100
                $path = $this->cleanPath($path);
101
            }
102
103
            if (!empty($path)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after NOT operator; 0 found
Loading history...
104
                $this->templatePath = $path;
105
                if ($this->twigEnabled) {
106
                    $this->twig->setLoader(new \Twig\Loader\FilesystemLoader(MODX_BASE_PATH . $path));
0 ignored issues
show
Bug introduced by
The method setLoader() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

106
                    $this->twig->/** @scrutinizer ignore-call */ 
107
                                 setLoader(new \Twig\Loader\FilesystemLoader(MODX_BASE_PATH . $path));

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Bug introduced by
The type Twig\Loader\FilesystemLoader was not found. Maybe you did not declare it correctly or list all dependencies?

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:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
107
                }
108
                if ($this->bladeEnabled) {
109
                    $filesystem = new Illuminate\Filesystem\Filesystem;
0 ignored issues
show
Bug introduced by
The type Illuminate\Filesystem\Filesystem was not found. Maybe you did not declare it correctly or list all dependencies?

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:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
110
                    $viewFinder = new Illuminate\View\FileViewFinder($filesystem, [MODX_BASE_PATH . $path]);
0 ignored issues
show
Bug introduced by
The type Illuminate\View\FileViewFinder was not found. Maybe you did not declare it correctly or list all dependencies?

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:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
111
                    $this->blade->setFinder($viewFinder);
112
                }
113
            }
114
115
            return $this;
116
        }
117
118
        /**
119
         * @param string $path
120
         * @return string
121
         */
122
        protected function cleanPath($path)
123
        {
124
            return preg_replace(array('/\.*[\/|\\\]/i', '/[\/|\\\]+/i'), array('/', '/'), $path);
125
        }
126
127
        public function getTemplateExtension()
128
        {
129
            return $this->templateExtension;
130
        }
131
132
        /**
133
         * Задает расширение файла с шаблоном
134
         *
135
         * @param $ext
136
         * @return $this
137
         */
138
        public function setTemplateExtension($ext)
139
        {
140
            $ext = $this->cleanPath(trim($ext ?? '', ". \t\n\r\0\x0B"));
141
142
            if (!empty($ext)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after NOT operator; 0 found
Loading history...
143 58
                $this->templateExtension = $ext;
144
            }
145 58
146 58
            return $this;
147 58
        }
148
149 58
        /**
150
         * Additional data for external templates
151
         *
152
         * @param array $data
153
         * @return $this
154
         */
155
        public function setTemplateData($data = array())
156
        {
157
            if (is_array($data)) {
0 ignored issues
show
introduced by
The condition is_array($data) is always true.
Loading history...
158
                $this->templateData = $data;
159
            }
160
161
            return $this;
162
        }
163
164
        /**
165
         * @param array $data
166
         * @return array
167
         */
168
        public function getTemplateData($data = array())
169
        {
170
            $plh = $this->templateData;
171
            $plh['data'] = $data;
172
            $plh['modx'] = $this->modx;
173
174
            return $plh;
175
        }
176
177
        /**
178
         * Сохранение данных в массив плейсхолдеров
179
         *
180
         * @param mixed $data данные
181
         * @param int $set устанавливать ли глобальнй плейсхолдер MODX
182
         * @param string $key ключ локального плейсхолдера
183
         * @param string $prefix префикс для ключей массива
184
         * @return string
185
         */
186
        public function toPlaceholders($data, $set = 0, $key = 'contentPlaceholder', $prefix = '')
187
        {
188
            $out = '';
189
            if ($set != 0) {
190
                $this->modx->toPlaceholder($key, $data, $prefix);
0 ignored issues
show
Bug introduced by
The method toPlaceholder() does not exist on DocumentParser. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

190
                $this->modx->/** @scrutinizer ignore-call */ 
191
                             toPlaceholder($key, $data, $prefix);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
191
            } else {
192
                $out = $data;
193
            }
194
195
            return $out;
196
        }
197
198
        /**
199
         * refactor $modx->getChunk();
200
         *
201
         * @param string $name Template: chunk name || @CODE: template || @FILE: file with template
202
         * @return string html template with placeholders without data
203
         */
204
        public function getChunk($name)
0 ignored issues
show
Coding Style introduced by
Function's nesting level (5) exceeds 3; consider refactoring the function
Loading history...
205
        {
206
            $tpl = '';
207
            $ext = null;
208
            $this->bladeEnabled = substr($name, 0, 3) == '@B_';//(0 === strpos($name, '@B_'));
209
            if ($name != '' && !isset($this->modx->chunkCache[$name])) {
0 ignored issues
show
Bug introduced by
The property chunkCache does not seem to exist on DocumentParser.
Loading history...
Coding Style introduced by
Expected 1 space after NOT operator; 0 found
Loading history...
210
                $mode = (preg_match(
211
                    '/^((@[A-Z_]+)[:]{0,1})(.*)/Asu',
212
                    trim($name),
213
                    $tmp
214
                ) && isset($tmp[2], $tmp[3])) ? $tmp[2] : false;
215
                $subTmp = (isset($tmp[3])) ? trim($tmp[3]) : null;
216
                if ($this->bladeEnabled) {
217
                    $ext = $this->getTemplateExtension();
218
                    $this->setTemplateExtension('blade.php');
219
                }
220
                switch ($mode) {
221
                    case '@T_FILE':
222
                        if ($subTmp != '' && $this->twigEnabled) {
223
                            $real = realpath(MODX_BASE_PATH . $this->templatePath);
224
                            $path = realpath(MODX_BASE_PATH . $this->templatePath . $this->cleanPath($subTmp) . '.' . $this->templateExtension);
225
                            if (basename($path, '.' . $this->templateExtension) !== '' &&
226
                                0 === strpos($path, $real) &&
227
                                file_exists($path)
228
                            ) {
229
                                $tpl = $this->twig->load($this->cleanPath($subTmp) . '.' . $this->templateExtension);
230
                            }
231
                        }
232
                        break;
233
                    case '@T_CODE':
234
                        if ($this->twigEnabled) {
235
                            $tpl = $tmp[3];
236
                            $tpl = $this->twig->createTemplate($tpl);
237
                        }
238
                        break;
239
                    case '@B_FILE':
240
                        if ($subTmp != '' && $this->bladeEnabled) {
241
                            $real = realpath(MODX_BASE_PATH . $this->templatePath);
242
                            $path = realpath(MODX_BASE_PATH . $this->templatePath . $this->cleanPath($subTmp) . '.' . $this->templateExtension);
243
                            if (basename($path, '.' . $this->templateExtension) !== '' &&
244
                                0 === strpos($path, $real) &&
245
                                file_exists($path)
246
                            ) {
247
                                $tpl = $this->cleanPath($subTmp);
248
                            }
249
                        }
250
                        break;
251
                    case '@B_CODE':
252
                        $cache = md5($name). '-'. sha1($subTmp);
0 ignored issues
show
Coding Style introduced by
Concat operator must be surrounded by a single space
Loading history...
Bug introduced by
It seems like $subTmp can also be of type null; however, parameter $string of sha1() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

252
                        $cache = md5($name). '-'. sha1(/** @scrutinizer ignore-type */ $subTmp);
Loading history...
253
                        $path = MODX_BASE_PATH . '/assets/cache/blade/' . $cache . '.blade.php';
254
                        if (! file_exists($path)) {
255
                            file_put_contents($path, $tpl);
256
                        }
257
                        $tpl = 'cache::' . $cache;
258
                        break;
259
                    case '@FILE':
260
                        if ($subTmp != '') {
261
                            $real = realpath(MODX_BASE_PATH . $this->templatePath);
262
                            $path = realpath(MODX_BASE_PATH . $this->templatePath . $this->cleanPath($subTmp) . '.' . $this->templateExtension);
263
                            if (basename($path, '.' . $this->templateExtension) !== '' &&
264
                                0 === strpos($path, $real) &&
265
                                file_exists($path)
266
                            ) {
267
                                $tpl = file_get_contents($path);
268
                            }
269
                        }
270
                        break;
271
                    case '@INLINE':
272
                    case '@TPL':
273
                    case '@CODE':
274
                        $tpl = $tmp[3]; //without trim
275
                        break;
276
                    case '@DOCUMENT':
277
                    case '@DOC':
278
                        switch (true) {
279
                            case ((int)$subTmp > 0):
280
                                $tpl = $this->modx->getPageInfo((int)$subTmp, 0, "content");
0 ignored issues
show
Bug introduced by
The method getPageInfo() does not exist on DocumentParser. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

280
                                /** @scrutinizer ignore-call */ 
281
                                $tpl = $this->modx->getPageInfo((int)$subTmp, 0, "content");

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
281
                                $tpl = isset($tpl['content']) ? $tpl['content'] : '';
282
                                break;
283
                            case ((int)$subTmp == 0):
284
                                $tpl = $this->modx->documentObject['content'];
0 ignored issues
show
Bug introduced by
The property documentObject does not seem to exist on DocumentParser.
Loading history...
285
                                break;
286
                        }
287
                        break;
288
                    case '@PLH':
289
                    case '@PLACEHOLDER':
290
                        if ($subTmp != '') {
291
                            $tpl = $this->modx->getPlaceholder($subTmp);
0 ignored issues
show
Bug introduced by
The method getPlaceholder() does not exist on DocumentParser. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

291
                            /** @scrutinizer ignore-call */ 
292
                            $tpl = $this->modx->getPlaceholder($subTmp);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
292
                        }
293
                        break;
294
                    case '@CFG':
295
                    case '@CONFIG':
296
                    case '@OPTIONS':
297
                        if ($subTmp != '') {
298
                            $tpl = $this->modx->getConfig($subTmp);
0 ignored issues
show
Bug introduced by
The method getConfig() does not exist on DocumentParser. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

298
                            /** @scrutinizer ignore-call */ 
299
                            $tpl = $this->modx->getConfig($subTmp);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
299
                        }
300
                        break;
301
                    case '@SNIPPET':
302
                        if ($subTmp != '') {
303
                            $tpl = $this->modx->runSnippet($subTmp, $this->modx->event->params);
0 ignored issues
show
Bug introduced by
The property event does not seem to exist on DocumentParser.
Loading history...
Bug introduced by
The method runSnippet() does not exist on DocumentParser. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

303
                            /** @scrutinizer ignore-call */ 
304
                            $tpl = $this->modx->runSnippet($subTmp, $this->modx->event->params);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
304
                        }
305
                        break;
306
                    case '@RENDERPAGE':
307
                        $tpl = $this->renderDoc($subTmp, false);
0 ignored issues
show
Bug introduced by
It seems like $subTmp can also be of type string; however, parameter $id of DLTemplate::renderDoc() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

307
                        $tpl = $this->renderDoc(/** @scrutinizer ignore-type */ $subTmp, false);
Loading history...
308
                        break;
309
                    case '@LOADPAGE':
310
                        $tpl = $this->renderDoc($subTmp, true);
311
                        break;
312
                    case '@TEMPLATE':
313
                        $tpl = $this->getTemplate($subTmp);
0 ignored issues
show
Bug introduced by
It seems like $subTmp can also be of type string; however, parameter $id of DLTemplate::getTemplate() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

313
                        $tpl = $this->getTemplate(/** @scrutinizer ignore-type */ $subTmp);
Loading history...
314
                        break;
315
                    case '@CHUNK':
316
                        $tpl = $this->getBaseChunk($subTmp);
317
                        break;
318
                    default:
319
                        $tpl = $this->getBaseChunk($name);
320
                }
321
                $this->modx->chunkCache[$name] = $tpl;
322
            } else {
323
                $tpl = $this->getBaseChunk($name);
324
            }
325
326
            if($ext !== null) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
327
                $this->setTemplateExtension($ext);
328
            }
329
            return $tpl;
330
        }
331
332
        protected function getBaseChunk($name)
333
        {
334
            if (empty($name)) {
335
                return '';
336
            }
337
338
            if (isset ($this->modx->chunkCache[$name])) {
0 ignored issues
show
Coding Style introduced by
Space before opening parenthesis of function call prohibited
Loading history...
Bug introduced by
The property chunkCache does not seem to exist on DocumentParser.
Loading history...
339
                $tpl = $this->modx->chunkCache[$name];
340
            } else {
341
                $table = $this->modx->getFullTableName('site_htmlsnippets');
342
                $query = $this->modx->db->query(
343
                    "SELECT `snippet` FROM " . $table . " WHERE `name`='" . $this->modx->db->escape($name) . "' AND `disabled`=0"
344
                );
345
                if ($this->modx->db->getRecordCount($query) == 1) {
346
                    $row = $this->modx->db->getRow($query);
347
                    $tpl = $row['snippet'];
348
                } else {
349
                    $tpl = '';
350
                }
351
            }
352
353
            return $tpl;
354
        }
355
356
        /**
357
         * Рендер документа с подстановкой плейсхолдеров и выполнением сниппетов
358
         *
359
         * @param int $id ID документа
360
         * @param bool $events Во время рендера документа стоит ли вызывать события OnLoadWebDocument и OnLoadDocumentObject (внутри метода getDocumentObject).
361
         * @param mixed $tpl Шаблон с которым необходимо отрендерить документ. Возможные значения:
362
         *                       null - Использовать шаблон который назначен документу
363
         *                       int(0-n) - Получить шаблон из базы данных с указанным ID и применить его к документу
364
         *                       string - Применить шаблон указанный в строке к документу
365
         * @return string
366
         *
367
         * Событие OnLoadWebDocument дополнительно передает параметры:
368
         *       - с источиком от куда произошел вызов события
369
         *       - оригинальный экземпляр класса DocumentParser
370
         */
371
        public function renderDoc($id, $events = false, $tpl = null)
372
        {
373
            $id = (int)$id;
374
            if ($id <= 0) {
375
                return '';
376
            }
377
378
            $m = clone $this->modx; //Чтобы была возможность вызывать события
379
            $m->documentIdentifier = $id;
380
            $m->documentObject = $m->getDocumentObject('id', (int)$id, $events ? 'prepareResponse' : null);
0 ignored issues
show
Bug introduced by
The property documentObject does not seem to exist on DocumentParser.
Loading history...
Bug introduced by
The method getDocumentObject() does not exist on DocumentParser. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

380
            /** @scrutinizer ignore-call */ 
381
            $m->documentObject = $m->getDocumentObject('id', (int)$id, $events ? 'prepareResponse' : null);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
381
            if ($m->documentObject['type'] == "reference") {
382
                if (is_numeric($m->documentObject['content']) && $m->documentObject['content'] > 0) {
383
                    $m->documentObject['content'] = $this->renderDoc($m->documentObject['content'], $events);
384
                }
385
            }
386
            switch (true) {
387
                case is_integer($tpl):
388
                    $tpl = $this->getTemplate($tpl);
389
                    break;
390
                case is_string($tpl):
391
                    break;
392
                case is_null($tpl):
393
                default:
394
                    $tpl = $this->getTemplate($m->documentObject['template']);
395
            }
396
            $m->documentContent = $tpl;
0 ignored issues
show
Bug introduced by
The property documentContent does not seem to exist on DocumentParser.
Loading history...
397
            if ($events) {
398
                $m->invokeEvent("OnLoadWebDocument", array(
0 ignored issues
show
Bug introduced by
The method invokeEvent() does not exist on DocumentParser. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

398
                $m->/** @scrutinizer ignore-call */ 
399
                    invokeEvent("OnLoadWebDocument", array(

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
399
                    'source'   => 'DLTemplate',
400
                    'mainModx' => $this->modx,
401
                ));
402
            }
403
404
            return $this->parseDocumentSource($m->documentContent, $m);
405
        }
406
407
        /**
408
         * Получить содержимое шаблона с определенным номером
409
         * @param int $id Номер шаблона
410
         * @return string HTML код шаблона
411
         */
412
        public function getTemplate($id)
413
        {
414
            $tpl = null;
415
            $id = (int)$id;
416
            if ($id > 0) {
417
                $tpl = $this->modx->db->getValue("SELECT `content` FROM {$this->modx->getFullTableName("site_templates")} WHERE `id` = {$id}");
418
            }
419
            if (is_null($tpl)) {
420
                $tpl = '[*content*]';
421
            }
422
423
            return $tpl;
424
        }
425
426
        /**
427
         * refactor $modx->parseChunk();
428
         *
429
         * @param string $name Template: chunk name || @CODE: template || @FILE: file with template
430
         * @param array $data paceholder
431
         * @param bool $parseDocumentSource render html template via DocumentParser::parseDocumentSource()
432
         * @return string html template with data without placeholders
433
         */
434
        public function parseChunk($name, $data = array(), $parseDocumentSource = false, $disablePHx = false)
0 ignored issues
show
Coding Style introduced by
Function's nesting level (4) exceeds 3; consider refactoring the function
Loading history...
435
        {
436
            $out = $this->getChunk($name);
437
            $twig = strpos($name, '@T_') === 0 && $this->twigEnabled;
438
            $blade = strpos($name, '@B_') === 0 && $this->bladeEnabled;
439
            switch (true) {
440
                case $twig:
441
                    $out = $out->render($this->getTemplateData($data));
442
                    break;
443
                case $blade:
444
                    $out = $this->blade->make($out)->with($this->getTemplateData($data))->render();
445
                    break;
446
                case is_array($data) && ($out != ''):
447
                    if (preg_match("/\[\+[A-Z0-9\.\_\-]+\+\]/is", $out)) {
448
                        $item = $this->renameKeyArr($data, '[', ']', '+');
449
                        $out = str_replace(array_keys($item), array_values($item), $out);
450
                    }
451
                    if (!$disablePHx && preg_match("/:([^:=]+)(?:=`(.*?)`(?=:[^:=]+|$))?/is", $out)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after NOT operator; 0 found
Loading history...
452
                        if (is_null($this->phx) || !($this->phx instanceof DLphx)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after NOT operator; 0 found
Loading history...
453
                            $this->phx = $this->createPHx(0, 1000);
454
                        }
455
                        $this->phx->placeholders = array();
456
                        $this->setPHxPlaceholders($data);
457
                        $out = $this->phx->Parse($out);
458
                    }
459
                    break;
460
            }
461
            if ($parseDocumentSource && !$twig && !$blade) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after NOT operator; 0 found
Loading history...
462
                $out = $this->parseDocumentSource($out);
463
            }
464
465
            return $out;
466
        }
467
468
        /**
469
         *
470
         * @param string|array $value
471
         * @param string $key
472
         * @param string $path
473
         */
474
        public function setPHxPlaceholders($value = '', $key = '', $path = '')
0 ignored issues
show
Coding Style introduced by
This method is not in camel caps format.

This check looks for method names that are not written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection seeker becomes databaseConnectionSeeker.

Loading history...
475
        {
476
            $keypath = !empty($path) ? $path . "." . $key : $key;
0 ignored issues
show
Coding Style introduced by
Expected 1 space after NOT operator; 0 found
Loading history...
477
            $this->phx->curPass = 0;
478
            if (is_array($value)) {
479
                foreach ($value as $subkey => $subval) {
480
                    $this->setPHxPlaceholders($subval, $subkey, $keypath);
481
                }
482
            } else {
483
                $this->phx->setPHxVariable($keypath, $value);
484
            }
485
        }
486
487
        public function loadTwig() {
488
            if (is_null($this->twig) && isset($this->modx->twig)) {
489
                $this->twig = clone $this->modx->twig;
490
                $this->twigEnabled = true;
491
            }
492
        }
493
494
        public function loadBlade() {
495
            if (is_null($this->blade) && isset($this->modx->blade)) {
496
                $this->blade = clone $this->modx->blade;
497
                $this->bladeEnabled = true;
498
            }
499
        }
500
501
        /**
502
         *
503
         * @param string $string
504
         * @return string
505
         */
506
        public function cleanPHx($string)
0 ignored issues
show
Coding Style introduced by
This method is not in camel caps format.

This check looks for method names that are not written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection seeker becomes databaseConnectionSeeker.

Loading history...
507
        {
508
            preg_match_all('~\[(\+|\*|\()([^:\+\[\]]+)([^\[\]]*?)(\1|\))\]~s', $string, $matches);
509
            if ($matches[0]) {
510
                $string = str_replace($matches[0], '', $string);
511
            }
512
513
            return $string;
514
        }
515
516
        /**
517
         * @param int $debug
518
         * @param int $maxpass
519
         * @return DLphx
520
         */
521
        public function createPHx($debug = 0, $maxpass = 50)
0 ignored issues
show
Coding Style introduced by
This method is not in camel caps format.

This check looks for method names that are not written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection seeker becomes databaseConnectionSeeker.

Loading history...
522
        {
523
            if (!class_exists('DLphx')) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after NOT operator; 0 found
Loading history...
524
                include_once(__DIR__ . '/DLphx.class.php');
525
            }
526
527
            return new DLphx($this->modx, $debug, $maxpass);
528
        }
529
530
        /**
531
         * Переменовывание элементов массива
532
         *
533
         * @param array $data массив с данными
534
         * @param string $prefix префикс ключей
535
         * @param string $suffix суффикс ключей
536
         * @param string $sep разделитель суффиксов, префиксов и ключей массива
537
         * @return array массив с переименованными ключами
538
         */
539
        public function renameKeyArr($data, $prefix = '', $suffix = '', $sep = '.')
540
        {
541
            return APIhelpers::renameKeyArr($data, $prefix, $suffix, $sep);
542
        }
543
544
        /**
545
         * @param $out
546
         * @param DocumentParser|null $modx
547
         * @return mixed|string
548
         */
549
        public function parseDocumentSource($out, $modx = null)
550
        {
551
            if (!is_object($modx)) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after NOT operator; 0 found
Loading history...
552
                $modx = $this->modx;
553
            }
554
            $_minPasses = (int)$modx->minParserPasses;
0 ignored issues
show
Bug introduced by
The property minParserPasses does not seem to exist on DocumentParser.
Loading history...
555
            $minPasses = $_minPasses <= 0 ? 2 : $_minPasses;
556
            $_maxPasses = (int)$modx->maxParserPasses;
0 ignored issues
show
Bug introduced by
The property maxParserPasses does not seem to exist on DocumentParser.
Loading history...
557
            $maxPasses = $_maxPasses <= 0 ? 10 : $_maxPasses;
558
            $modx->minParserPasses = $modx->maxParserPasses = 1;
559
            $site_status = $modx->getConfig('site_status');
560
            $modx->config['site_status'] = 0;
561
            for ($i = 1; $i <= $maxPasses; $i++) {
562
                $html = $out;
563
                if (preg_match('/\[\!(.*)\!\]/us', $out)) {
564
                    $out = str_replace(array('[!', '!]'), array('[[', ']]'), $out);
565
                }
566
                if ($i <= $minPasses || $out != $html) {
567
                    $out = $modx->parseDocumentSource($out);
0 ignored issues
show
Bug introduced by
The method parseDocumentSource() does not exist on DocumentParser. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

567
                    /** @scrutinizer ignore-call */ 
568
                    $out = $modx->parseDocumentSource($out);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
568
                } else {
569
                    break;
570
                }
571
            }
572
            $out = $modx->rewriteUrls($out);
0 ignored issues
show
Bug introduced by
The method rewriteUrls() does not exist on DocumentParser. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

572
            /** @scrutinizer ignore-call */ 
573
            $out = $modx->rewriteUrls($out);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
573
            $out = $this->cleanPHx($out);
574
            $modx->config['site_status'] = $site_status;
575
            $modx->minParserPasses = $_minPasses;
576
            $modx->maxParserPasses = $_maxPasses;
577
            
578
            return $out;
579
        }
580
    }
581
}
582