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

Cecilapp / Cecil / 21143795213

19 Jan 2026 03:54PM UTC coverage: 82.274%. First build
21143795213

Pull #2285

github

web-flow
Merge 40c08ca9d into 878eab640
Pull Request #2285: Integrate PHP-DI for dependency injection

58 of 83 new or added lines in 16 files covered. (69.88%)

3328 of 4045 relevant lines covered (82.27%)

0.82 hits per line

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

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

3
/**
4
 * This file is part of Cecil.
5
 *
6
 * (c) Arnaud Ligny <arnaud@ligny.fr>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11

12
declare(strict_types=1);
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\Config;
20
use Cecil\Exception\ConfigException;
21
use Cecil\Exception\RuntimeException;
22
use Cecil\Renderer\Config as RendererConfig;
23
use Cecil\Renderer\Layout;
24
use Cecil\Renderer\Page as PageRenderer;
25
use Cecil\Renderer\Site;
26
use Cecil\Renderer\Twig;
27
use Cecil\Renderer\Twig\TwigFactory;
28
use Cecil\Step\AbstractStep;
29
use Cecil\Util;
30
use DI\Attribute\Inject;
31
use Psr\Log\LoggerInterface;
32

33
/**
34
 * Render step.
35
 *
36
 * This step is responsible for rendering pages using Twig templates.
37
 * It processes each page, applies the appropriate templates, and generates
38
 * the final output formats. It also handles subsets of pages if specified,
39
 * and adds global variables to the renderer. The rendered pages are then
40
 * stored in the builder's pages collection for further processing or output.
41
 */
42
class Render extends AbstractStep
43
{
44
    public const TMP_DIR = '.cecil';
45

46
    protected $subset = [];
47

48
    #[Inject]
49
    private TwigFactory $twigFactory;
50

51
    /**
52
     * {@inheritdoc}
53
     */
54
    public function getName(): string
55
    {
56
        return 'Rendering pages';
1✔
57
    }
58

59
    /**
60
     * {@inheritdoc}
61
     */
62
    public function init(array $options): void
63
    {
64
        if (!is_dir($this->config->getLayoutsPath()) && !$this->config->hasTheme()) {
1✔
65
            $message = \sprintf('"%s" is not a valid layouts directory', $this->config->getLayoutsPath());
×
NEW
66
            $this->logger->debug($message);
×
67
        }
68

69
        // render a subset of pages?
70
        if (!empty($options['render-subset'])) {
1✔
71
            $subset = \sprintf('pages.subsets.%s', (string) $options['render-subset']);
×
72
            if (!$this->config->has($subset)) {
×
73
                throw new ConfigException(\sprintf('Subset "%s" not found.', $subset));
×
74
            }
75
            $this->subset = (array) $this->config->get($subset);
×
76
        }
77

78
        $this->canProcess = true;
1✔
79
    }
80

81
    /**
82
     * {@inheritdoc}
83
     *
84
     * @throws RuntimeException
85
     */
86
    public function process(): void
87
    {
88
        // prepares renderer
89
        $this->builder->setRenderer($this->twigFactory->create($this->getAllLayoutsPaths()));
1✔
90

91
        // adds global variables
92
        $this->addGlobals();
1✔
93

94
        $subset = $this->subset;
1✔
95

96
        /** @var Collection $pages */
97
        $pages = $this->builder->getPages()
1✔
98
            // published only
1✔
99
            ->filter(function (Page $page) {
1✔
100
                return (bool) $page->getVariable('published');
1✔
101
            })
1✔
102
            ->filter(function (Page $page) use ($subset) {
1✔
103
                if (empty($subset)) {
1✔
104
                    return true;
1✔
105
                }
106
                if (
107
                    !empty($subset['path'])
×
108
                    && !((bool) preg_match('/' . (string) $subset['path'] . '/i', $page->getPath()))
×
109
                ) {
110
                    return false;
×
111
                }
112
                if (!empty($subset['language'])) {
×
113
                    $language = $page->getVariable('language', $this->config->getLanguageDefault());
×
114
                    if ($language !== (string) $subset['language']) {
×
115
                        return false;
×
116
                    }
117
                }
118
                return true;
×
119
            })
1✔
120
            // enrichs some variables
1✔
121
            ->map(function (Page $page) {
1✔
122
                $formats = $this->getOutputFormats($page);
1✔
123
                // output formats
124
                $page->setVariable('output', $formats);
1✔
125
                // alternates formats
126
                $page->setVariable('alternates', $this->getAlternates($formats));
1✔
127
                // translations
128
                $page->setVariable('translations', $this->getTranslations($page));
1✔
129

130
                return $page;
1✔
131
            });
1✔
132
        $total = \count($pages);
1✔
133

134
        // renders each page
135
        $count = 0;
1✔
136
        $postprocessors = [];
1✔
137
        foreach ((array) $this->config->get('output.postprocessors') as $name => $postprocessor) {
1✔
138
            try {
139
                if (!class_exists($postprocessor)) {
1✔
140
                    throw new RuntimeException(\sprintf('Class "%s" not found', $postprocessor));
1✔
141
                }
142
                $postprocessors[] = new $postprocessor($this->builder);
1✔
143
                $this->logger->debug(\sprintf('Output post processor "%s" loaded', $name));
1✔
144
            } catch (\Exception $e) {
1✔
145
                $this->logger->error(\sprintf('Unable to load output post processor "%s": %s', $name, $e->getMessage()));
1✔
146
            }
147
        }
148

149
        // some cache to avoid multiple calls
150
        $cache = [];
1✔
151

152
        /** @var Page $page */
153
        foreach ($pages as $page) {
1✔
154
            $count++;
1✔
155
            $rendered = [];
1✔
156

157
            // l10n
158
            $language = $page->getVariable('language', $this->config->getLanguageDefault());
1✔
159
            if (!isset($cache['locale'][$language])) {
1✔
160
                $cache['locale'][$language] = $this->config->getLanguageProperty('locale', $language);
1✔
161
            }
162
            $this->builder->getRenderer()->setLocale($cache['locale'][$language]);
1✔
163

164
            // global site variables
165
            if (!isset($cache['site'][$language])) {
1✔
166
                $cache['site'][$language] = new Site($this->builder, $language);
1✔
167
            }
168
            $this->builder->getRenderer()->addGlobal('site', $cache['site'][$language]);
1✔
169

170
            // global config raw variables
171
            if (!isset($cache['config'][$language])) {
1✔
172
                $cache['config'][$language] = new RendererConfig($this->builder, $language);
1✔
173
            }
174
            $this->builder->getRenderer()->addGlobal('config', $cache['config'][$language]);
1✔
175

176
            // excluded format(s)?
177
            $formats = (array) $page->getVariable('output');
1✔
178
            foreach ($formats as $key => $format) {
1✔
179
                if ($exclude = $this->config->getOutputFormatProperty($format, 'exclude')) {
1✔
180
                    // ie:
181
                    //   formats:
182
                    //     atom:
183
                    //       [...]
184
                    //       exclude: [paginated]
185
                    if (!\is_array($exclude)) {
1✔
186
                        $exclude = [$exclude];
×
187
                    }
188
                    foreach ($exclude as $variable) {
1✔
189
                        if ($page->hasVariable($variable)) {
1✔
190
                            unset($formats[$key]);
1✔
191
                        }
192
                    }
193
                }
194
            }
195

196
            // specific output format from subset
197
            if (!empty($this->subset['output'])) {
1✔
198
                $currentFormats = $formats;
×
199
                $formats = [];
×
200
                if (\in_array((string) $this->subset['output'], $currentFormats)) {
×
201
                    $formats = [(string) $this->subset['output']];
×
202
                }
203
            }
204

205
            // renders each output format
206
            foreach ($formats as $format) {
1✔
207
                // search for the template
208
                $layout = Layout::finder($page, $format, $this->config);
1✔
209
                // renders with Twig
210
                try {
211
                    $deprecations = [];
1✔
212
                    set_error_handler(function ($type, $msg) use (&$deprecations) {
1✔
213
                        if (E_USER_DEPRECATED === $type) {
1✔
214
                            $deprecations[] = $msg;
1✔
215
                        }
216
                    });
1✔
217
                    $output = $this->builder->getRenderer()->render($layout['file'], ['page' => $page]);
1✔
218
                    foreach ($deprecations as $value) {
1✔
219
                        $this->builder->getLogger()->warning($value);
1✔
220
                    }
221
                    foreach ($postprocessors as $postprocessor) {
1✔
222
                        $output = $postprocessor->process($page, $output, $format);
1✔
223
                    }
224
                    $rendered[$format] = [
1✔
225
                        'output'   => $output,
1✔
226
                        'template' => [
1✔
227
                            'scope' => $layout['scope'],
1✔
228
                            'file'  => $layout['file'],
1✔
229
                        ],
1✔
230
                    ];
1✔
231
                    $page->addRendered($rendered);
1✔
232
                } catch (\Twig\Error\Error $e) {
×
233
                    throw new RuntimeException(
×
234
                        \sprintf(
×
235
                            'Unable to render template "%s" for page "%s".',
×
236
                            $e->getSourceContext()->getName(),
×
237
                            $page->getFileName() ?? $page->getId()
×
238
                        ),
×
239
                        previous: $e,
×
240
                        file: $e->getSourceContext()->getPath(),
×
241
                        line: $e->getTemplateLine(),
×
242
                    );
×
243
                } catch (\Exception $e) {
×
244
                    throw new RuntimeException($e->getMessage(), previous: $e);
×
245
                }
246
            }
247
            $this->builder->getPages()->replace($page->getId(), $page);
1✔
248

249
            $templates = array_column($rendered, 'template');
1✔
250
            $message = \sprintf(
1✔
251
                'Page "%s" rendered with [%s]',
1✔
252
                $page->getId() ?: 'index',
1✔
253
                Util\Str::combineArrayToString($templates, 'scope', 'file')
1✔
254
            );
1✔
255
            $this->builder->getLogger()->info($message, ['progress' => [$count, $total]]);
1✔
256
        }
257
        // profiler
258
        if ($this->builder->isDebug()) {
1✔
259
            try {
260
                // HTML
261
                $htmlDumper = new \Twig\Profiler\Dumper\HtmlDumper();
1✔
262
                $profileHtmlFile = Util::joinFile($this->config->getDestinationDir(), self::TMP_DIR, 'twig_profile.html');
1✔
263
                Util\File::getFS()->dumpFile($profileHtmlFile, $htmlDumper->dump($this->builder->getRenderer()->getDebugProfile()));
1✔
264
                // TXT
265
                $textDumper = new \Twig\Profiler\Dumper\TextDumper();
1✔
266
                $profileTextFile = Util::joinFile($this->config->getDestinationDir(), self::TMP_DIR, 'twig_profile.txt');
1✔
267
                Util\File::getFS()->dumpFile($profileTextFile, $textDumper->dump($this->builder->getRenderer()->getDebugProfile()));
1✔
268
                // log
269
                $this->builder->getLogger()->debug(\sprintf('Twig profile dumped in "%s"', Util::joinFile($this->config->getDestinationDir(), self::TMP_DIR)));
1✔
270
            } catch (\Symfony\Component\Filesystem\Exception\IOException $e) {
×
271
                throw new RuntimeException($e->getMessage());
×
272
            }
273
        }
274
    }
275

276
    /**
277
     * Returns an array of layouts directories.
278
     */
279
    protected function getAllLayoutsPaths(): array
280
    {
281
        $paths = [];
1✔
282

283
        // layouts/
284
        if (is_dir($this->config->getLayoutsPath())) {
1✔
285
            $paths[] = $this->config->getLayoutsPath();
1✔
286
        }
287
        // <theme>/layouts/
288
        if ($this->config->hasTheme()) {
1✔
289
            foreach ($this->config->getTheme() ?? [] as $theme) {
1✔
290
                $paths[] = $this->config->getThemeDirPath($theme);
1✔
291
            }
292
        }
293
        // resources/layouts/
294
        if (is_dir($this->config->getLayoutsInternalPath())) {
1✔
295
            $paths[] = $this->config->getLayoutsInternalPath();
1✔
296
        }
297

298
        return $paths;
1✔
299
    }
300

301
    /**
302
     * Adds global variables.
303
     */
304
    protected function addGlobals()
305
    {
306
        $this->builder->getRenderer()->addGlobal('cecil', [
1✔
307
            'url'       => \sprintf('https://cecil.app/#%s', Builder::getVersion()),
1✔
308
            'version'   => Builder::getVersion(),
1✔
309
            'poweredby' => \sprintf('Cecil v%s', Builder::getVersion()),
1✔
310
        ]);
1✔
311
    }
312

313
    /**
314
     * Get available output formats.
315
     *
316
     * @throws RuntimeException
317
     */
318
    protected function getOutputFormats(Page $page): array
319
    {
320
        // Get page output format(s) if defined.
321
        // ie:
322
        // ```yaml
323
        // output: txt
324
        // ```
325
        if ($page->getVariable('output')) {
1✔
326
            $formats = $page->getVariable('output');
1✔
327
            if (!\is_array($formats)) {
1✔
328
                $formats = [$formats];
1✔
329
            }
330

331
            return $formats;
1✔
332
        }
333

334
        // Get available output formats for the page type.
335
        // ie:
336
        // ```yaml
337
        // page: [html, json]
338
        // ```
339
        $formats = $this->config->get('output.pagetypeformats.' . $page->getType());
1✔
340
        if (empty($formats)) {
1✔
341
            throw new RuntimeException('Configuration key "pagetypeformats" can\'t be empty.');
×
342
        }
343
        if (!\is_array($formats)) {
1✔
344
            $formats = [$formats];
×
345
        }
346

347
        return array_unique($formats);
1✔
348
    }
349

350
    /**
351
     * Get alternates.
352
     */
353
    protected function getAlternates(array $formats): array
354
    {
355
        $alternates = [];
1✔
356

357
        if (\count($formats) > 1 || \in_array('html', $formats)) {
1✔
358
            foreach ($formats as $format) {
1✔
359
                $format == 'html' ? $rel = 'canonical' : $rel = 'alternate';
1✔
360
                $alternates[] = [
1✔
361
                    'rel'    => $rel,
1✔
362
                    'type'   => $this->config->getOutputFormatProperty($format, 'mediatype'),
1✔
363
                    'title'  => strtoupper($format),
1✔
364
                    'format' => $format,
1✔
365
                ];
1✔
366
            }
367
        }
368

369
        return $alternates;
1✔
370
    }
371

372
    /**
373
     * Returns the collection of translated pages for a given page.
374
     */
375
    protected function getTranslations(Page $refPage): Collection
376
    {
377
        $pages = $this->builder->getPages()->filter(function (Page $page) use ($refPage) {
1✔
378
            return $page->getVariable('langref') == $refPage->getVariable('langref')
1✔
379
                && $page->getType() == $refPage->getType()
1✔
380
                && $page->getId() !== $refPage->getId()
1✔
381
                && !empty($page->getVariable('published'))
1✔
382
                && !$page->getVariable('paginated')
1✔
383
            ;
1✔
384
        });
1✔
385

386
        return $pages;
1✔
387
    }
388
}
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