Passed
Pull Request — master (#2062)
by Arnaud
13:15 queued 05:14
created

Render::process()   F

Complexity

Conditions 19
Paths 3030

Size

Total Lines 134
Code Lines 76

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 75
CRAP Score 19.5871

Importance

Changes 0
Metric Value
cc 19
eloc 76
nc 3030
nop 0
dl 0
loc 134
ccs 75
cts 85
cp 0.8824
crap 19.5871
rs 0.3499
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
                    // profiler
164 1
                    if ($this->builder->isDebug()) {
165 1
                        $dumper = new \Twig\Profiler\Dumper\HtmlDumper();
166 1
                        file_put_contents(
167 1
                            Util::joinFile($this->config->getOutputPath(), '_debug_twig_profile.html'),
168 1
                            $dumper->dump($this->builder->getRenderer()->getDebugProfile())
169 1
                        );
170
                    }
171
                } catch (\Twig\Error\Error $e) {
172
                    $template = !empty($e->getSourceContext()->getPath()) ? $e->getSourceContext()->getPath() : $e->getSourceContext()->getName();
173
174
                    throw new RuntimeException(\sprintf(
175
                        'Template "%s%s" (page: %s): %s',
176
                        $template,
177
                        $e->getTemplateLine() >= 0 ? \sprintf(':%s', $e->getTemplateLine()) : '',
178
                        $page->getId(),
179
                        $e->getMessage()
180
                    ));
181
                }
182
            }
183 1
            $this->builder->getPages()->replace($page->getId(), $page);
184
185 1
            $templates = array_column($rendered, 'template');
186 1
            $message = \sprintf(
187 1
                'Page "%s" rendered with [%s]',
188 1
                $page->getId() ?: 'index',
189 1
                Util\Str::combineArrayToString($templates, 'scope', 'file')
190 1
            );
191 1
            $this->builder->getLogger()->info($message, ['progress' => [$count, $total]]);
192
        }
193
    }
194
195
    /**
196
     * Returns an array of layouts directories.
197
     */
198 1
    protected function getAllLayoutsPaths(): array
199
    {
200 1
        $paths = [];
201
202
        // layouts/
203 1
        if (is_dir($this->config->getLayoutsPath())) {
204 1
            $paths[] = $this->config->getLayoutsPath();
205
        }
206
        // <theme>/layouts/
207 1
        if ($this->config->hasTheme()) {
208 1
            $themes = $this->config->getTheme();
209 1
            foreach ($themes as $theme) {
210 1
                $paths[] = $this->config->getThemeDirPath($theme);
211
            }
212
        }
213
        // resources/layouts/
214 1
        if (is_dir($this->config->getLayoutsInternalPath())) {
215 1
            $paths[] = $this->config->getLayoutsInternalPath();
216
        }
217
218 1
        return $paths;
219
    }
220
221
    /**
222
     * Adds global variables.
223
     */
224 1
    protected function addGlobals()
225
    {
226 1
        $this->builder->getRenderer()->addGlobal('cecil', [
227 1
            'url'       => \sprintf('https://cecil.app/#%s', Builder::getVersion()),
228 1
            'version'   => Builder::getVersion(),
229 1
            'poweredby' => \sprintf('Cecil v%s', Builder::getVersion()),
230 1
        ]);
231
    }
232
233
    /**
234
     * Get available output formats.
235
     *
236
     * @throws RuntimeException
237
     */
238 1
    protected function getOutputFormats(Page $page): array
239
    {
240
        // Get page output format(s) if defined.
241
        // ie:
242
        // ```yaml
243
        // output: txt
244
        // ```
245 1
        if ($page->getVariable('output')) {
246 1
            $formats = $page->getVariable('output');
247 1
            if (!\is_array($formats)) {
248 1
                $formats = [$formats];
249
            }
250
251 1
            return $formats;
252
        }
253
254
        // Get available output formats for the page type.
255
        // ie:
256
        // ```yaml
257
        // page: [html, json]
258
        // ```
259 1
        $formats = $this->config->get('output.pagetypeformats.' . $page->getType());
260 1
        if (empty($formats)) {
261
            throw new RuntimeException('Configuration key "pagetypeformats" can\'t be empty.');
262
        }
263 1
        if (!\is_array($formats)) {
264
            $formats = [$formats];
265
        }
266
267 1
        return $formats;
268
    }
269
270
    /**
271
     * Get alternates.
272
     */
273 1
    protected function getAlternates(array $formats): array
274
    {
275 1
        $alternates = [];
276
277 1
        if (\count($formats) > 1 || \in_array('html', $formats)) {
278 1
            foreach ($formats as $format) {
279 1
                $format == 'html' ? $rel = 'canonical' : $rel = 'alternate';
280 1
                $alternates[] = [
281 1
                    'rel'    => $rel,
282 1
                    'type'   => $this->config->getOutputFormatProperty($format, 'mediatype'),
283 1
                    'title'  => strtoupper($format),
284 1
                    'format' => $format,
285 1
                ];
286
            }
287
        }
288
289 1
        return $alternates;
290
    }
291
292
    /**
293
     * Returns the collection of translated pages for a given page.
294
     */
295 1
    protected function getTranslations(Page $refPage): \Cecil\Collection\Page\Collection
296
    {
297 1
        $pages = $this->builder->getPages()->filter(function (Page $page) use ($refPage) {
298 1
            return $page->getId() !== $refPage->getId()
299 1
                && $page->getVariable('langref') == $refPage->getVariable('langref')
300 1
                && $page->getType() == $refPage->getType()
301 1
                && !empty($page->getVariable('published'))
302 1
                && !$page->getVariable('paginated');
303 1
        });
304
305 1
        return $pages;
306
    }
307
}
308