Render   C
last analyzed

Complexity

Total Complexity 57

Size/Duplication

Total Lines 343
Duplicated Lines 0 %

Importance

Changes 3
Bugs 1 Features 1
Metric Value
eloc 164
c 3
b 1
f 1
dl 0
loc 343
rs 5.04
wmc 57

8 Methods

Rating   Name   Duplication   Size   Complexity  
A getName() 0 3 1
A getAlternates() 0 17 5
A addGlobals() 0 6 1
A init() 0 17 5
A getOutputFormats() 0 30 5
A getAllLayoutsPaths() 0 20 5
F process() 0 186 29
A getTranslations() 0 13 6

How to fix   Complexity   

Complex Class

Complex classes like Render 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 Render, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * This file is part of Cecil.
5
 *
6
 * (c) Arnaud Ligny <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Cecil\Step\Pages;
15
16
use Cecil\Builder;
17
use Cecil\Collection\Page\Collection;
18
use Cecil\Collection\Page\Page;
19
use Cecil\Exception\ConfigException;
20
use Cecil\Exception\RuntimeException;
21
use Cecil\Renderer\Config;
22
use Cecil\Renderer\Layout;
23
use Cecil\Renderer\Site;
24
use Cecil\Renderer\Twig;
25
use Cecil\Step\AbstractStep;
26
use Cecil\Util;
27
28
/**
29
 * Render step.
30
 *
31
 * This step is responsible for rendering pages using Twig templates.
32
 * It processes each page, applies the appropriate templates, and generates
33
 * the final output formats. It also handles subsets of pages if specified,
34
 * and adds global variables to the renderer. The rendered pages are then
35
 * stored in the builder's pages collection for further processing or output.
36
 */
37
class Render extends AbstractStep
38
{
39
    public const TMP_DIR = '.cecil';
40
41
    protected $subset = [];
42
43
    /**
44
     * {@inheritdoc}
45
     */
46
    public function getName(): string
47
    {
48
        return 'Rendering pages';
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54
    public function init(array $options): void
55
    {
56
        if (!is_dir($this->config->getLayoutsPath()) && !$this->config->hasTheme()) {
57
            $message = \sprintf('"%s" is not a valid layouts directory', $this->config->getLayoutsPath());
58
            $this->builder->getLogger()->debug($message);
59
        }
60
61
        // render a subset of pages?
62
        if (!empty($options['render-subset'])) {
63
            $subset = \sprintf('pages.subsets.%s', (string) $options['render-subset']);
64
            if (!$this->config->has($subset)) {
65
                throw new ConfigException(\sprintf('Subset "%s" not found.', $subset));
66
            }
67
            $this->subset = (array) $this->config->get($subset);
68
        }
69
70
        $this->canProcess = true;
71
    }
72
73
    /**
74
     * {@inheritdoc}
75
     *
76
     * @throws RuntimeException
77
     */
78
    public function process(): void
79
    {
80
        // prepares renderer
81
        $this->builder->setRenderer(new Twig($this->builder, $this->getAllLayoutsPaths()));
82
83
        // adds global variables
84
        $this->addGlobals();
85
86
        $subset = $this->subset;
87
88
        /** @var Collection $pages */
89
        $pages = $this->builder->getPages()
90
            // published only
91
            ->filter(function (Page $page) {
92
                return (bool) $page->getVariable('published');
93
            })
94
            ->filter(function (Page $page) use ($subset) {
95
                if (empty($subset)) {
96
                    return true;
97
                }
98
                if (
99
                    !empty($subset['path'])
100
                    && !((bool) preg_match('/' . (string) $subset['path'] . '/i', $page->getPath()))
101
                ) {
102
                    return false;
103
                }
104
                if (!empty($subset['language'])) {
105
                    $language = $page->getVariable('language', $this->config->getLanguageDefault());
106
                    if ($language !== (string) $subset['language']) {
107
                        return false;
108
                    }
109
                }
110
                return true;
111
            })
112
            // enrichs some variables
113
            ->map(function (Page $page) {
114
                $formats = $this->getOutputFormats($page);
115
                // output formats
116
                $page->setVariable('output', $formats);
117
                // alternates formats
118
                $page->setVariable('alternates', $this->getAlternates($formats));
119
                // translations
120
                $page->setVariable('translations', $this->getTranslations($page));
121
122
                return $page;
123
            });
124
        $total = \count($pages);
125
126
        // renders each page
127
        $count = 0;
128
        $postprocessors = [];
129
        foreach ((array) $this->config->get('output.postprocessors') as $name => $postprocessor) {
130
            try {
131
                if (!class_exists($postprocessor)) {
132
                    throw new RuntimeException(\sprintf('Class "%s" not found', $postprocessor));
133
                }
134
                $postprocessors[] = new $postprocessor($this->builder);
135
                $this->builder->getLogger()->debug(\sprintf('Output post processor "%s" loaded', $name));
136
            } catch (\Exception $e) {
137
                $this->builder->getLogger()->error(\sprintf('Unable to load output post processor "%s": %s', $name, $e->getMessage()));
138
            }
139
        }
140
141
        // some caches to avoid multiple calls
142
        $cacheLocale = $cacheSite = $cacheConfig = [];
143
144
        /** @var Page $page */
145
        foreach ($pages as $page) {
146
            $count++;
147
            $rendered = [];
148
149
            // l10n
150
            $language = $page->getVariable('language', $this->config->getLanguageDefault());
151
            if (!isset($cacheLocale[$language])) {
152
                $cacheLocale[$language] = $this->config->getLanguageProperty('locale', $language);
153
            }
154
            $this->builder->getRenderer()->setLocale($cacheLocale[$language]);
155
156
            // global site variables
157
            if (!isset($cacheSite[$language])) {
158
                $cacheSite[$language] = new Site($this->builder, $language);
159
            }
160
            $this->builder->getRenderer()->addGlobal('site', $cacheSite[$language]);
161
162
            // global config raw variables
163
            if (!isset($cacheConfig[$language])) {
164
                $cacheConfig[$language] = new Config($this->builder, $language);
165
            }
166
            $this->builder->getRenderer()->addGlobal('config', $cacheConfig[$language]);
167
168
            // excluded format(s)?
169
            $formats = (array) $page->getVariable('output');
170
            foreach ($formats as $key => $format) {
171
                if ($exclude = $this->config->getOutputFormatProperty($format, 'exclude')) {
172
                    // ie:
173
                    //   formats:
174
                    //     atom:
175
                    //       [...]
176
                    //       exclude: [paginated]
177
                    if (!\is_array($exclude)) {
178
                        $exclude = [$exclude];
179
                    }
180
                    foreach ($exclude as $variable) {
181
                        if ($page->hasVariable($variable)) {
182
                            unset($formats[$key]);
183
                        }
184
                    }
185
                }
186
            }
187
188
            // specific output format from subset
189
            if (!empty($this->subset['output'])) {
190
                $currentFormats = $formats;
191
                $formats = [];
192
                if (\in_array((string) $this->subset['output'], $currentFormats)) {
193
                    $formats = [(string) $this->subset['output']];
194
                }
195
            }
196
197
            // renders each output format
198
            foreach ($formats as $format) {
199
                // search for the template
200
                $layout = Layout::finder($page, $format, $this->config);
201
                // renders with Twig
202
                try {
203
                    $deprecations = [];
204
                    set_error_handler(function ($type, $msg) use (&$deprecations) {
205
                        if (E_USER_DEPRECATED === $type) {
206
                            $deprecations[] = $msg;
207
                        }
208
                    });
209
                    $output = $this->builder->getRenderer()->render($layout['file'], ['page' => $page]);
210
                    foreach ($deprecations as $value) {
211
                        $this->builder->getLogger()->warning($value);
212
                    }
213
                    foreach ($postprocessors as $postprocessor) {
214
                        $output = $postprocessor->process($page, $output, $format);
215
                    }
216
                    $rendered[$format] = [
217
                        'output'   => $output,
218
                        'template' => [
219
                            'scope' => $layout['scope'],
220
                            'file'  => $layout['file'],
221
                        ],
222
                    ];
223
                    $page->addRendered($rendered);
224
                } catch (\Twig\Error\Error $e) {
225
                    throw new RuntimeException(
226
                        \sprintf(
227
                            'Can\'t render template "%s" for page "%s".',
228
                            $e->getSourceContext()->getName(),
229
                            $page->getFileName() ?? $page->getId()
230
                        ),
231
                        previous: $e,
232
                        file: $e->getSourceContext()->getPath(),
233
                        line: $e->getTemplateLine(),
234
                    );
235
                } catch (\Exception $e) {
236
                    throw new RuntimeException($e->getMessage(), previous: $e);
237
                }
238
            }
239
            $this->builder->getPages()->replace($page->getId(), $page);
240
241
            $templates = array_column($rendered, 'template');
242
            $message = \sprintf(
243
                'Page "%s" rendered with [%s]',
244
                $page->getId() ?: 'index',
245
                Util\Str::combineArrayToString($templates, 'scope', 'file')
246
            );
247
            $this->builder->getLogger()->info($message, ['progress' => [$count, $total]]);
248
        }
249
        // profiler
250
        if ($this->builder->isDebug()) {
251
            try {
252
                // HTML
253
                $htmlDumper = new \Twig\Profiler\Dumper\HtmlDumper();
254
                $profileHtmlFile = Util::joinFile($this->config->getDestinationDir(), self::TMP_DIR, 'twig_profile.html');
255
                Util\File::getFS()->dumpFile($profileHtmlFile, $htmlDumper->dump($this->builder->getRenderer()->getDebugProfile()));
256
                // TXT
257
                $textDumper = new \Twig\Profiler\Dumper\TextDumper();
258
                $profileTextFile = Util::joinFile($this->config->getDestinationDir(), self::TMP_DIR, 'twig_profile.txt');
259
                Util\File::getFS()->dumpFile($profileTextFile, $textDumper->dump($this->builder->getRenderer()->getDebugProfile()));
260
                // log
261
                $this->builder->getLogger()->debug(\sprintf('Twig profile dumped in "%s"', Util::joinFile($this->config->getDestinationDir(), self::TMP_DIR)));
262
            } catch (\Symfony\Component\Filesystem\Exception\IOException $e) {
263
                throw new RuntimeException($e->getMessage());
264
            }
265
        }
266
    }
267
268
    /**
269
     * Returns an array of layouts directories.
270
     */
271
    protected function getAllLayoutsPaths(): array
272
    {
273
        $paths = [];
274
275
        // layouts/
276
        if (is_dir($this->config->getLayoutsPath())) {
277
            $paths[] = $this->config->getLayoutsPath();
278
        }
279
        // <theme>/layouts/
280
        if ($this->config->hasTheme()) {
281
            foreach ($this->config->getTheme() ?? [] as $theme) {
282
                $paths[] = $this->config->getThemeDirPath($theme);
283
            }
284
        }
285
        // resources/layouts/
286
        if (is_dir($this->config->getLayoutsInternalPath())) {
287
            $paths[] = $this->config->getLayoutsInternalPath();
288
        }
289
290
        return $paths;
291
    }
292
293
    /**
294
     * Adds global variables.
295
     */
296
    protected function addGlobals()
297
    {
298
        $this->builder->getRenderer()->addGlobal('cecil', [
299
            'url'       => \sprintf('https://cecil.app/#%s', Builder::getVersion()),
300
            'version'   => Builder::getVersion(),
301
            'poweredby' => \sprintf('Cecil v%s', Builder::getVersion()),
302
        ]);
303
    }
304
305
    /**
306
     * Get available output formats.
307
     *
308
     * @throws RuntimeException
309
     */
310
    protected function getOutputFormats(Page $page): array
311
    {
312
        // Get page output format(s) if defined.
313
        // ie:
314
        // ```yaml
315
        // output: txt
316
        // ```
317
        if ($page->getVariable('output')) {
318
            $formats = $page->getVariable('output');
319
            if (!\is_array($formats)) {
320
                $formats = [$formats];
321
            }
322
323
            return $formats;
324
        }
325
326
        // Get available output formats for the page type.
327
        // ie:
328
        // ```yaml
329
        // page: [html, json]
330
        // ```
331
        $formats = $this->config->get('output.pagetypeformats.' . $page->getType());
332
        if (empty($formats)) {
333
            throw new RuntimeException('Configuration key "pagetypeformats" can\'t be empty.');
334
        }
335
        if (!\is_array($formats)) {
336
            $formats = [$formats];
337
        }
338
339
        return array_unique($formats);
340
    }
341
342
    /**
343
     * Get alternates.
344
     */
345
    protected function getAlternates(array $formats): array
346
    {
347
        $alternates = [];
348
349
        if (\count($formats) > 1 || \in_array('html', $formats)) {
350
            foreach ($formats as $format) {
351
                $format == 'html' ? $rel = 'canonical' : $rel = 'alternate';
352
                $alternates[] = [
353
                    'rel'    => $rel,
354
                    'type'   => $this->config->getOutputFormatProperty($format, 'mediatype'),
355
                    'title'  => strtoupper($format),
356
                    'format' => $format,
357
                ];
358
            }
359
        }
360
361
        return $alternates;
362
    }
363
364
    /**
365
     * Returns the collection of translated pages for a given page.
366
     */
367
    protected function getTranslations(Page $refPage): Collection
368
    {
369
        $pages = $this->builder->getPages()->filter(function (Page $page) use ($refPage) {
370
            return $page->getId() !== $refPage->getId()
371
                && $page->getVariable('langref') == $refPage->getVariable('langref')
372
                && $page->getType() == $refPage->getType()
373
                && !empty($page->getVariable('published'))
374
                && !$page->getVariable('paginated')
375
                && !$page->isVirtual()
376
            ;
377
        });
378
379
        return $pages;
380
    }
381
}
382