Passed
Pull Request — master (#1877)
by Arnaud
10:36 queued 04:44
created

Render::getOutputFormats()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 30
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5.1158

Importance

Changes 0
Metric Value
cc 5
eloc 11
nc 5
nop 1
dl 0
loc 30
ccs 10
cts 12
cp 0.8333
crap 5.1158
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 $postprocessor) {
90 1
            $name = $postprocessor;
91 1
            $postprocessor = "Cecil\Renderer\PostProcessor\\$postprocessor";
92 1
            if (!class_exists($postprocessor)) {
93 1
                $this->builder->getLogger()->error(sprintf('Can\'t load output post processor "%s"', $postprocessor));
94 1
                break;
95
            }
96 1
            $postprocessors[] = new $postprocessor($this->builder);
97 1
            $this->builder->getLogger()->debug(sprintf('Output post processor "%s" loaded', $name));
98
        }
99
        /** @var Page $page */
100 1
        foreach ($pages as $page) {
101 1
            $count++;
102 1
            $rendered = [];
103
104
            // l10n
105 1
            $language = $page->getVariable('language', $this->config->getLanguageDefault());
106 1
            $locale = $this->config->getLanguageProperty('locale', $language);
107 1
            $this->builder->getRenderer()->setLocale($locale);
108
109
            // global site variables
110 1
            $this->builder->getRenderer()->addGlobal('site', new Site($this->builder, $language));
111
112
            // global config raw variables
113 1
            $this->builder->getRenderer()->addGlobal('config', new Config($this->builder, $language));
114
115
            // excluded format(s)?
116 1
            $formats = (array) $page->getVariable('output');
117 1
            foreach ($formats as $key => $format) {
118 1
                if ($exclude = $this->config->getOutputFormatProperty($format, 'exclude')) {
119
                    // ie:
120
                    //   formats:
121
                    //     atom:
122
                    //       [...]
123
                    //       exclude: [paginated]
124 1
                    if (!\is_array($exclude)) {
125
                        $exclude = [$exclude];
126
                    }
127 1
                    foreach ($exclude as $variable) {
128 1
                        if ($page->hasVariable($variable)) {
129 1
                            unset($formats[$key]);
130
                        }
131
                    }
132
                }
133
            }
134
135
            // renders each output format
136 1
            foreach ($formats as $format) {
137
                // search for the template
138 1
                $layout = Layout::finder($page, $format, $this->config);
139
                // renders with Twig
140
                try {
141 1
                    $deprecations = [];
142 1
                    set_error_handler(function ($type, $msg) use (&$deprecations) {
143 1
                        if (E_USER_DEPRECATED === $type) {
144
                            $deprecations[] = $msg;
145
                        }
146 1
                    });
147 1
                    $output = $this->builder->getRenderer()->render($layout['file'], ['page' => $page]);
148 1
                    foreach ($deprecations as $value) {
149
                        $this->builder->getLogger()->warning($value);
150
                    }
151 1
                    foreach ($postprocessors as $postprocessor) {
152 1
                        $output = $postprocessor->process($page, $output, $format);
153
                    }
154 1
                    $rendered[$format] = [
155 1
                        'output'   => $output,
156 1
                        'template' => [
157 1
                            'scope' => $layout['scope'],
158 1
                            'file'  => $layout['file'],
159 1
                        ],
160 1
                    ];
161 1
                    $page->addRendered($rendered);
162
                    // profiler
163 1
                    if ($this->builder->isDebug()) {
164 1
                        $dumper = new \Twig\Profiler\Dumper\HtmlDumper();
165 1
                        file_put_contents(
166 1
                            Util::joinFile($this->config->getOutputPath(), '_debug_twig_profile.html'),
167 1
                            $dumper->dump($this->builder->getRenderer()->getDebugProfile())
168 1
                        );
169
                    }
170
                } catch (\Twig\Error\Error $e) {
171
                    $template = !empty($e->getSourceContext()->getPath()) ? $e->getSourceContext()->getPath() : $e->getSourceContext()->getName();
172
173
                    throw new RuntimeException(sprintf(
174
                        'Template "%s%s" (page: %s): %s',
175
                        $template,
176
                        $e->getTemplateLine() >= 0 ? sprintf(':%s', $e->getTemplateLine()) : '',
177
                        $page->getId(),
178
                        $e->getMessage()
179
                    ));
180
                }
181
            }
182 1
            $this->builder->getPages()->replace($page->getId(), $page);
183
184 1
            $templates = array_column($rendered, 'template');
185 1
            $message = sprintf(
186 1
                'Page "%s" rendered with [%s]',
187 1
                $page->getId() ?: 'index',
188 1
                Util\Str::combineArrayToString($templates, 'scope', 'file')
189 1
            );
190 1
            $this->builder->getLogger()->info($message, ['progress' => [$count, $total]]);
191
        }
192
    }
193
194
    /**
195
     * Returns an array of layouts directories.
196
     */
197 1
    protected function getAllLayoutsPaths(): array
198
    {
199 1
        $paths = [];
200
201
        // layouts/
202 1
        if (is_dir($this->config->getLayoutsPath())) {
203 1
            $paths[] = $this->config->getLayoutsPath();
204
        }
205
        // <theme>/layouts/
206 1
        if ($this->config->hasTheme()) {
207 1
            $themes = $this->config->getTheme();
208 1
            foreach ($themes as $theme) {
209 1
                $paths[] = $this->config->getThemeDirPath($theme);
210
            }
211
        }
212
        // resources/layouts/
213 1
        if (is_dir($this->config->getLayoutsInternalPath())) {
214 1
            $paths[] = $this->config->getLayoutsInternalPath();
215
        }
216
217 1
        return $paths;
218
    }
219
220
    /**
221
     * Adds global variables.
222
     */
223 1
    protected function addGlobals()
224
    {
225 1
        $this->builder->getRenderer()->addGlobal('cecil', [
226 1
            'url'       => sprintf('https://cecil.app/#%s', Builder::getVersion()),
227 1
            'version'   => Builder::getVersion(),
228 1
            'poweredby' => sprintf('Cecil v%s', Builder::getVersion()),
229 1
        ]);
230
    }
231
232
    /**
233
     * Get available output formats.
234
     *
235
     * @throws RuntimeException
236
     */
237 1
    protected function getOutputFormats(Page $page): array
238
    {
239
        // Get page output format(s) if defined.
240
        // ie:
241
        // ```yaml
242
        // output: txt
243
        // ```
244 1
        if ($page->getVariable('output')) {
245 1
            $formats = $page->getVariable('output');
246 1
            if (!\is_array($formats)) {
247 1
                $formats = [$formats];
248
            }
249
250 1
            return $formats;
251
        }
252
253
        // Get available output formats for the page type.
254
        // ie:
255
        // ```yaml
256
        // page: [html, json]
257
        // ```
258 1
        $formats = $this->config->get('output.pagetypeformats.' . $page->getType());
259 1
        if (empty($formats)) {
260
            throw new RuntimeException('Configuration key "pagetypeformats" can\'t be empty.');
261
        }
262 1
        if (!\is_array($formats)) {
263
            $formats = [$formats];
264
        }
265
266 1
        return $formats;
267
    }
268
269
    /**
270
     * Get alternates.
271
     */
272 1
    protected function getAlternates(array $formats): array
273
    {
274 1
        $alternates = [];
275
276 1
        if (\count($formats) > 1 || \in_array('html', $formats)) {
277 1
            foreach ($formats as $format) {
278 1
                $format == 'html' ? $rel = 'canonical' : $rel = 'alternate';
279 1
                $alternates[] = [
280 1
                    'rel'    => $rel,
281 1
                    'type'   => $this->config->getOutputFormatProperty($format, 'mediatype'),
282 1
                    'title'  => strtoupper($format),
283 1
                    'format' => $format,
284 1
                ];
285
            }
286
        }
287
288 1
        return $alternates;
289
    }
290
291
    /**
292
     * Returns the collection of translated pages for a given page.
293
     */
294 1
    protected function getTranslations(Page $refPage): \Cecil\Collection\Page\Collection
295
    {
296 1
        $pages = $this->builder->getPages()->filter(function (Page $page) use ($refPage) {
297 1
            return $page->getId() !== $refPage->getId()
298 1
                && $page->getVariable('langref') == $refPage->getVariable('langref')
299 1
                && $page->getType() == $refPage->getType()
300 1
                && !empty($page->getVariable('published'))
301 1
                && !$page->getVariable('paginated');
302 1
        });
303
304 1
        return $pages;
305
    }
306
}
307