• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Cecilapp / Cecil / 15444845771

04 Jun 2025 02:19PM UTC coverage: 82.811% (+0.04%) from 82.775%
15444845771

push

github

ArnaudLigny
refactor: code quality

5 of 5 new or added lines in 1 file covered. (100.0%)

17 existing lines in 3 files now uncovered.

3117 of 3764 relevant lines covered (82.81%)

0.83 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

78.82
/src/Step/Pages/Render.php
1
<?php
2

3
declare(strict_types=1);
4

5
/*
6
 * This file is part of Cecil.
7
 *
8
 * Copyright (c) Arnaud Ligny <arnaud@ligny.fr>
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\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
 * Pages rendering.
30
 */
31
class Render extends AbstractStep
32
{
33
    public const TMP_DIR = '.cecil';
34

35
    protected $subset = [];
36

37
    /**
38
     * {@inheritdoc}
39
     */
40
    public function getName(): string
41
    {
42
        return 'Rendering pages';
1✔
43
    }
44

45
    /**
46
     * {@inheritdoc}
47
     */
48
    public function init(array $options): void
49
    {
50
        if (!is_dir($this->config->getLayoutsPath()) && !$this->config->hasTheme()) {
1✔
51
            $message = \sprintf('"%s" is not a valid layouts directory', $this->config->getLayoutsPath());
×
52
            $this->builder->getLogger()->debug($message);
×
53
        }
54

55
        // render a subset of pages?
56
        if (!empty($options['render-subset'])) {
1✔
57
            $subset = \sprintf('pages.subsets.%s', (string) $options['render-subset']);
×
58
            if (!$this->config->has($subset)) {
×
59
                throw new ConfigException(\sprintf('Subset "%s" not found.', $subset));
×
60
            }
61
            $this->subset = (array) $this->config->get($subset);
×
62
        }
63

64
        $this->canProcess = true;
1✔
65
    }
66

67
    /**
68
     * {@inheritdoc}
69
     *
70
     * @throws RuntimeException
71
     */
72
    public function process(): void
73
    {
74
        // prepares renderer
75
        $this->builder->setRenderer(new Twig($this->builder, $this->getAllLayoutsPaths()));
1✔
76

77
        // adds global variables
78
        $this->addGlobals();
1✔
79

80
        $subset = $this->subset;
1✔
81

82
        /** @var Collection $pages */
83
        $pages = $this->builder->getPages()
1✔
84
            // published only
1✔
85
            ->filter(function (Page $page) {
1✔
86
                return (bool) $page->getVariable('published');
1✔
87
            })
1✔
88
            ->filter(function (Page $page) use ($subset) {
1✔
89
                if (empty($subset)) {
1✔
90
                    return true;
1✔
91
                }
92
                if (
93
                    !empty($subset['path'])
×
94
                    && !((bool) preg_match('/' . (string) $subset['path'] . '/i', $page->getPath()))
×
95
                ) {
96
                    return false;
×
97
                }
98
                if (!empty($subset['language'])) {
×
99
                    $language = $page->getVariable('language', $this->config->getLanguageDefault());
×
100
                    if ($language !== (string) $subset['language']) {
×
101
                        return false;
×
102
                    }
103
                }
104
                return true;
×
105
            })
1✔
106
            // enrichs some variables
1✔
107
            ->map(function (Page $page) {
1✔
108
                $formats = $this->getOutputFormats($page);
1✔
109
                // output formats
110
                $page->setVariable('output', $formats);
1✔
111
                // alternates formats
112
                $page->setVariable('alternates', $this->getAlternates($formats));
1✔
113
                // translations
114
                $page->setVariable('translations', $this->getTranslations($page));
1✔
115

116
                return $page;
1✔
117
            });
1✔
118
        $total = \count($pages);
1✔
119

120
        // renders each page
121
        $count = 0;
1✔
122
        $postprocessors = [];
1✔
123
        foreach ((array) $this->config->get('output.postprocessors') as $name => $postprocessor) {
1✔
124
            try {
125
                if (!class_exists($postprocessor)) {
1✔
126
                    throw new RuntimeException(\sprintf('Class "%s" not found', $postprocessor));
1✔
127
                }
128
                $postprocessors[] = new $postprocessor($this->builder);
1✔
129
                $this->builder->getLogger()->debug(\sprintf('Output post processor "%s" loaded', $name));
1✔
130
            } catch (\Exception $e) {
1✔
131
                $this->builder->getLogger()->error(\sprintf('Unable to load output post processor "%s": %s', $name, $e->getMessage()));
1✔
132
            }
133
        }
134

135
        // some caches to avoid multiple calls
136
        $cacheLocale = $cacheSite = $cacheConfig = [];
1✔
137

138
        /** @var Page $page */
139
        foreach ($pages as $page) {
1✔
140
            $count++;
1✔
141
            $rendered = [];
1✔
142

143
            // l10n
144
            $language = $page->getVariable('language', $this->config->getLanguageDefault());
1✔
145
            if (!isset($cacheLocale[$language])) {
1✔
146
                $cacheLocale[$language] = $this->config->getLanguageProperty('locale', $language);
1✔
147
            }
148
            $this->builder->getRenderer()->setLocale($cacheLocale[$language]);
1✔
149

150
            // global site variables
151
            if (!isset($cacheSite[$language])) {
1✔
152
                $cacheSite[$language] = new Site($this->builder, $language);
1✔
153
            }
154
            $this->builder->getRenderer()->addGlobal('site', $cacheSite[$language]);
1✔
155

156
            // global config raw variables
157
            if (!isset($cacheConfig[$language])) {
1✔
158
                $cacheConfig[$language] = new Config($this->builder, $language);
1✔
159
            }
160
            $this->builder->getRenderer()->addGlobal('config', $cacheConfig[$language]);
1✔
161

162
            // excluded format(s)?
163
            $formats = (array) $page->getVariable('output');
1✔
164
            foreach ($formats as $key => $format) {
1✔
165
                if ($exclude = $this->config->getOutputFormatProperty($format, 'exclude')) {
1✔
166
                    // ie:
167
                    //   formats:
168
                    //     atom:
169
                    //       [...]
170
                    //       exclude: [paginated]
171
                    if (!\is_array($exclude)) {
1✔
UNCOV
172
                        $exclude = [$exclude];
×
173
                    }
174
                    foreach ($exclude as $variable) {
1✔
175
                        if ($page->hasVariable($variable)) {
1✔
176
                            unset($formats[$key]);
1✔
177
                        }
178
                    }
179
                }
180
            }
181

182
            // specific output format from subset
183
            if (!empty($this->subset['output'])) {
1✔
184
                $currentFormats = $formats;
×
185
                $formats = [];
×
186
                if (\in_array((string) $this->subset['output'], $currentFormats)) {
×
UNCOV
187
                    $formats = [(string) $this->subset['output']];
×
188
                }
189
            }
190

191
            // renders each output format
192
            foreach ($formats as $format) {
1✔
193
                // search for the template
194
                $layout = Layout::finder($page, $format, $this->config);
1✔
195
                // renders with Twig
196
                try {
197
                    $deprecations = [];
1✔
198
                    set_error_handler(function ($type, $msg) use (&$deprecations) {
1✔
199
                        if (E_USER_DEPRECATED === $type) {
1✔
200
                            $deprecations[] = $msg;
1✔
201
                        }
202
                    });
1✔
203
                    $output = $this->builder->getRenderer()->render($layout['file'], ['page' => $page]);
1✔
204
                    foreach ($deprecations as $value) {
1✔
205
                        $this->builder->getLogger()->warning($value);
1✔
206
                    }
207
                    foreach ($postprocessors as $postprocessor) {
1✔
208
                        $output = $postprocessor->process($page, $output, $format);
1✔
209
                    }
210
                    $rendered[$format] = [
1✔
211
                        'output'   => $output,
1✔
212
                        'template' => [
1✔
213
                            'scope' => $layout['scope'],
1✔
214
                            'file'  => $layout['file'],
1✔
215
                        ],
1✔
216
                    ];
1✔
217
                    $page->addRendered($rendered);
1✔
218
                } catch (\Twig\Error\Error $e) {
×
219
                    throw new RuntimeException(
×
220
                        \sprintf(
×
221
                            'Can\'t render template "%s" for page "%s".',
×
222
                            $e->getSourceContext()->getName(),
×
223
                            $page->getFileName() ?? $page->getId()
×
224
                        ),
×
225
                        previous: $e,
×
226
                        file: $e->getSourceContext()->getPath(),
×
227
                        line: $e->getTemplateLine(),
×
228
                    );
×
229
                } catch (\Exception $e) {
×
UNCOV
230
                    throw new RuntimeException($e->getMessage(), previous: $e);
×
231
                }
232
            }
233
            $this->builder->getPages()->replace($page->getId(), $page);
1✔
234

235
            $templates = array_column($rendered, 'template');
1✔
236
            $message = \sprintf(
1✔
237
                'Page "%s" rendered with [%s]',
1✔
238
                $page->getId() ?: 'index',
1✔
239
                Util\Str::combineArrayToString($templates, 'scope', 'file')
1✔
240
            );
1✔
241
            $this->builder->getLogger()->info($message, ['progress' => [$count, $total]]);
1✔
242
        }
243
        // profiler
244
        if ($this->builder->isDebug()) {
1✔
245
            try {
246
                // HTML
247
                $htmlDumper = new \Twig\Profiler\Dumper\HtmlDumper();
1✔
248
                $profileHtmlFile = Util::joinFile($this->config->getDestinationDir(), self::TMP_DIR, 'twig_profile.html');
1✔
249
                Util\File::getFS()->dumpFile($profileHtmlFile, $htmlDumper->dump($this->builder->getRenderer()->getDebugProfile()));
1✔
250
                // TXT
251
                $textDumper = new \Twig\Profiler\Dumper\TextDumper();
1✔
252
                $profileTextFile = Util::joinFile($this->config->getDestinationDir(), self::TMP_DIR, 'twig_profile.txt');
1✔
253
                Util\File::getFS()->dumpFile($profileTextFile, $textDumper->dump($this->builder->getRenderer()->getDebugProfile()));
1✔
254
                // log
255
                $this->builder->getLogger()->debug(\sprintf('Twig profile dumped in "%s"', Util::joinFile($this->config->getDestinationDir(), self::TMP_DIR)));
1✔
256
            } catch (\Symfony\Component\Filesystem\Exception\IOException $e) {
×
UNCOV
257
                throw new RuntimeException($e->getMessage());
×
258
            }
259
        }
260
    }
261

262
    /**
263
     * Returns an array of layouts directories.
264
     */
265
    protected function getAllLayoutsPaths(): array
266
    {
267
        $paths = [];
1✔
268

269
        // layouts/
270
        if (is_dir($this->config->getLayoutsPath())) {
1✔
271
            $paths[] = $this->config->getLayoutsPath();
1✔
272
        }
273
        // <theme>/layouts/
274
        if ($this->config->hasTheme()) {
1✔
275
            foreach ($this->config->getTheme() ?? [] as $theme) {
1✔
276
                $paths[] = $this->config->getThemeDirPath($theme);
1✔
277
            }
278
        }
279
        // resources/layouts/
280
        if (is_dir($this->config->getLayoutsInternalPath())) {
1✔
281
            $paths[] = $this->config->getLayoutsInternalPath();
1✔
282
        }
283

284
        return $paths;
1✔
285
    }
286

287
    /**
288
     * Adds global variables.
289
     */
290
    protected function addGlobals()
291
    {
292
        $this->builder->getRenderer()->addGlobal('cecil', [
1✔
293
            'url'       => \sprintf('https://cecil.app/#%s', Builder::getVersion()),
1✔
294
            'version'   => Builder::getVersion(),
1✔
295
            'poweredby' => \sprintf('Cecil v%s', Builder::getVersion()),
1✔
296
        ]);
1✔
297
    }
298

299
    /**
300
     * Get available output formats.
301
     *
302
     * @throws RuntimeException
303
     */
304
    protected function getOutputFormats(Page $page): array
305
    {
306
        // Get page output format(s) if defined.
307
        // ie:
308
        // ```yaml
309
        // output: txt
310
        // ```
311
        if ($page->getVariable('output')) {
1✔
312
            $formats = $page->getVariable('output');
1✔
313
            if (!\is_array($formats)) {
1✔
314
                $formats = [$formats];
1✔
315
            }
316

317
            return $formats;
1✔
318
        }
319

320
        // Get available output formats for the page type.
321
        // ie:
322
        // ```yaml
323
        // page: [html, json]
324
        // ```
325
        $formats = $this->config->get('output.pagetypeformats.' . $page->getType());
1✔
326
        if (empty($formats)) {
1✔
UNCOV
327
            throw new RuntimeException('Configuration key "pagetypeformats" can\'t be empty.');
×
328
        }
329
        if (!\is_array($formats)) {
1✔
UNCOV
330
            $formats = [$formats];
×
331
        }
332

333
        return array_unique($formats);
1✔
334
    }
335

336
    /**
337
     * Get alternates.
338
     */
339
    protected function getAlternates(array $formats): array
340
    {
341
        $alternates = [];
1✔
342

343
        if (\count($formats) > 1 || \in_array('html', $formats)) {
1✔
344
            foreach ($formats as $format) {
1✔
345
                $format == 'html' ? $rel = 'canonical' : $rel = 'alternate';
1✔
346
                $alternates[] = [
1✔
347
                    'rel'    => $rel,
1✔
348
                    'type'   => $this->config->getOutputFormatProperty($format, 'mediatype'),
1✔
349
                    'title'  => strtoupper($format),
1✔
350
                    'format' => $format,
1✔
351
                ];
1✔
352
            }
353
        }
354

355
        return $alternates;
1✔
356
    }
357

358
    /**
359
     * Returns the collection of translated pages for a given page.
360
     */
361
    protected function getTranslations(Page $refPage): Collection
362
    {
363
        $pages = $this->builder->getPages()->filter(function (Page $page) use ($refPage) {
1✔
364
            return $page->getId() !== $refPage->getId()
1✔
365
                && $page->getVariable('langref') == $refPage->getVariable('langref')
1✔
366
                && $page->getType() == $refPage->getType()
1✔
367
                && !empty($page->getVariable('published'))
1✔
368
                && !$page->getVariable('paginated');
1✔
369
        });
1✔
370

371
        return $pages;
1✔
372
    }
373
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc