Passed
Pull Request — master (#2172)
by Franck
05:03
created

Render   B

Complexity

Total Complexity 46

Size/Duplication

Total Lines 303
Duplicated Lines 0 %

Test Coverage

Coverage 85.99%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 141
c 1
b 0
f 0
dl 0
loc 303
rs 8.72
ccs 135
cts 157
cp 0.8599
wmc 46

8 Methods

Rating   Name   Duplication   Size   Complexity  
A getAlternates() 0 17 5
A addGlobals() 0 6 1
A getOutputFormats() 0 30 5
A getTranslations() 0 11 5
A getName() 0 3 1
A init() 0 12 4
A getAllLayoutsPaths() 0 20 5
F process() 0 153 20

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