Passed
Pull Request — master (#2126)
by Arnaud
10:41 queued 04:09
created

Render::getAllLayoutsPaths()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 20
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

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