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

Cecilapp / Cecil / 15430169804

03 Jun 2025 11:47PM UTC coverage: 82.783% (-0.2%) from 82.968%
15430169804

Pull #2172

github

web-flow
Merge e90a2f4f6 into 6a4cc24a4
Pull Request #2172: Build Command : Allow to render a subset

23 of 38 new or added lines in 3 files covered. (60.53%)

167 existing lines in 3 files now uncovered.

3111 of 3758 relevant lines covered (82.78%)

0.83 hits per line

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

79.29
/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\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
    public const TMP_DIR = '.cecil';
33

34
    protected $subset = [];
35

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

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

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

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

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

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

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

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

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

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

134
        $cacheLocale = $cacheSite = $cacheConfig = [];
1✔
135

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

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

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

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

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

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

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

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

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

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

282
        return $paths;
1✔
283
    }
284

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

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

315
            return $formats;
1✔
316
        }
317

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

331
        return array_unique($formats);
1✔
332
    }
333

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

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

353
        return $alternates;
1✔
354
    }
355

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

369
        return $pages;
1✔
370
    }
371
}
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