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

Cecilapp / Cecil / 7135108204

07 Dec 2023 11:10PM UTC coverage: 82.976% (+0.4%) from 82.534%
7135108204

Pull #1676

github

web-flow
Merge ce0d85209 into 814daa587
Pull Request #1676: 8.x dev

184 of 222 new or added lines in 31 files covered. (82.88%)

15 existing lines in 5 files now uncovered.

2861 of 3448 relevant lines covered (82.98%)

0.83 hits per line

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

86.15
/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
    /**
33
     * {@inheritdoc}
34
     */
35
    public function getName(): string
36
    {
37
        return 'Rendering pages';
1✔
38
    }
39

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

50
        $this->canProcess = true;
1✔
51
    }
52

53
    /**
54
     * {@inheritdoc}
55
     *
56
     * @throws RuntimeException
57
     */
58
    public function process(): void
59
    {
60
        // prepares renderer
61
        $this->builder->setRenderer(new Twig($this->builder, $this->getAllLayoutsPaths()));
1✔
62

63
        // adds global variables
64
        $this->addGlobals();
1✔
65

66
        /** @var Collection $pages */
67
        $pages = $this->builder->getPages()
1✔
68
            // published only
1✔
69
            ->filter(function (Page $page) {
1✔
70
                return (bool) $page->getVariable('published');
1✔
71
            })
1✔
72
            // enrichs some variables
1✔
73
            ->map(function (Page $page) {
1✔
74
                $formats = $this->getOutputFormats($page);
1✔
75
                // output formats
76
                $page->setVariable('output', $formats);
1✔
77
                // alternates formats
78
                $page->setVariable('alternates', $this->getAlternates($formats));
1✔
79
                // translations
80
                $page->setVariable('translations', $this->getTranslations($page));
1✔
81

82
                return $page;
1✔
83
            });
1✔
84
        $total = \count($pages);
1✔
85

86
        // renders each page
87
        $count = 0;
1✔
88
        Util::autoload($this->builder, 'postprocessors');
1✔
89
        /** @var Page $page */
90
        foreach ($pages as $page) {
1✔
91
            $count++;
1✔
92
            $rendered = [];
1✔
93

94
            // l10n
95
            $language = $page->getVariable('language', $this->config->getLanguageDefault());
1✔
96
            $locale = $this->config->getLanguageProperty('locale', $language);
1✔
97
            $this->builder->getRenderer()->setLocale($locale);
1✔
98

99
            // global site variables
100
            $this->builder->getRenderer()->addGlobal('site', new Site($this->builder, $language));
1✔
101

102
            // global config raw variables
103
            $this->builder->getRenderer()->addGlobal('config', new Config($this->builder, $language));
1✔
104

105
            // excluded format(s)?
106
            $formats = (array) $page->getVariable('output');
1✔
107
            foreach ($formats as $key => $format) {
1✔
108
                if ($exclude = $this->config->getOutputFormatProperty($format, 'exclude')) {
1✔
109
                    // ie:
110
                    //   formats:
111
                    //     atom:
112
                    //       [...]
113
                    //       exclude: [paginated]
114
                    if (!\is_array($exclude)) {
1✔
115
                        $exclude = [$exclude];
×
116
                    }
117
                    foreach ($exclude as $variable) {
1✔
118
                        if ($page->hasVariable($variable)) {
1✔
119
                            unset($formats[$key]);
1✔
120
                        }
121
                    }
122
                }
123
            }
124

125
            // renders each output format
126
            foreach ($formats as $format) {
1✔
127
                // search for the template
128
                $layout = Layout::finder($page, $format, $this->config);
1✔
129
                // renders with Twig
130
                try {
131
                    $deprecations = [];
1✔
132
                    set_error_handler(function ($type, $msg) use (&$deprecations) {
1✔
133
                        if (E_USER_DEPRECATED === $type) {
1✔
UNCOV
134
                            $deprecations[] = $msg;
×
135
                        }
136
                    });
1✔
137
                    $output = $this->builder->getRenderer()->render($layout['file'], ['page' => $page]);
1✔
138
                    foreach ($deprecations as $value) {
1✔
UNCOV
139
                        $this->builder->getLogger()->warning($value);
×
140
                    }
141
                    foreach ($this->config->get('output.postprocessors') as $processor) {
1✔
142
                        if (!class_exists($processor)) {
1✔
NEW
143
                            $this->builder->getLogger()->error(sprintf('Can\'t load output post processor "%s"', $processor));
×
NEW
144
                            break;
×
145
                        }
146
                        $output = (new $processor($this->builder))->process($page, $output, $format);
1✔
147
                    }
148
                    $rendered[$format] = [
1✔
149
                        'output'   => $output,
1✔
150
                        'template' => [
1✔
151
                            'scope' => $layout['scope'],
1✔
152
                            'file'  => $layout['file'],
1✔
153
                        ],
1✔
154
                    ];
1✔
155
                    $page->addRendered($rendered);
1✔
156
                    // profiler
157
                    if ($this->builder->isDebug()) {
1✔
158
                        $dumper = new \Twig\Profiler\Dumper\HtmlDumper();
1✔
159
                        file_put_contents(
1✔
160
                            Util::joinFile($this->config->getOutputPath(), '_debug_twig_profile.html'),
1✔
161
                            $dumper->dump($this->builder->getRenderer()->getDebugProfile())
1✔
162
                        );
1✔
163
                    }
164
                } catch (\Twig\Error\Error $e) {
×
165
                    $template = !empty($e->getSourceContext()->getPath()) ? $e->getSourceContext()->getPath() : $e->getSourceContext()->getName();
×
166

167
                    throw new RuntimeException(sprintf(
×
168
                        'Template "%s%s" (page: %s): %s',
×
169
                        $template,
×
170
                        $e->getTemplateLine() >= 0 ? sprintf(':%s', $e->getTemplateLine()) : '',
×
171
                        $page->getId(),
×
172
                        $e->getMessage()
×
173
                    ));
×
174
                }
175
            }
176
            $this->builder->getPages()->replace($page->getId(), $page);
1✔
177

178
            $templates = array_column($rendered, 'template');
1✔
179
            $message = sprintf(
1✔
180
                'Page "%s" rendered with [%s]',
1✔
181
                $page->getId() ?: 'index',
1✔
182
                Util\Str::combineArrayToString($templates, 'scope', 'file')
1✔
183
            );
1✔
184
            $this->builder->getLogger()->info($message, ['progress' => [$count, $total]]);
1✔
185
        }
186
    }
187

188
    /**
189
     * Returns an array of layouts directories.
190
     */
191
    protected function getAllLayoutsPaths(): array
192
    {
193
        $paths = [];
1✔
194

195
        // layouts/
196
        if (is_dir($this->config->getLayoutsPath())) {
1✔
197
            $paths[] = $this->config->getLayoutsPath();
1✔
198
        }
199
        // <theme>/layouts/
200
        if ($this->config->hasTheme()) {
1✔
201
            $themes = $this->config->getTheme();
1✔
202
            foreach ($themes as $theme) {
1✔
203
                $paths[] = $this->config->getThemeDirPath($theme);
1✔
204
            }
205
        }
206
        // resources/layouts/
207
        if (is_dir($this->config->getLayoutsInternalPath())) {
1✔
208
            $paths[] = $this->config->getLayoutsInternalPath();
1✔
209
        }
210

211
        return $paths;
1✔
212
    }
213

214
    /**
215
     * Adds global variables.
216
     */
217
    protected function addGlobals()
218
    {
219
        $this->builder->getRenderer()->addGlobal('cecil', [
1✔
220
            'url'       => sprintf('https://cecil.app/#%s', Builder::getVersion()),
1✔
221
            'version'   => Builder::getVersion(),
1✔
222
            'poweredby' => sprintf('Cecil v%s', Builder::getVersion()),
1✔
223
        ]);
1✔
224
    }
225

226
    /**
227
     * Get available output formats.
228
     *
229
     * @throws RuntimeException
230
     */
231
    protected function getOutputFormats(Page $page): array
232
    {
233
        // Get page output format(s) if defined.
234
        // ie:
235
        // ```yaml
236
        // output: txt
237
        // ```
238
        if ($page->getVariable('output')) {
1✔
239
            $formats = $page->getVariable('output');
1✔
240
            if (!\is_array($formats)) {
1✔
241
                $formats = [$formats];
1✔
242
            }
243

244
            return $formats;
1✔
245
        }
246

247
        // Get available output formats for the page type.
248
        // ie:
249
        // ```yaml
250
        // page: [html, json]
251
        // ```
252
        $formats = $this->config->get('output.pagetypeformats.' . $page->getType());
1✔
253
        if (empty($formats)) {
1✔
254
            throw new RuntimeException('Configuration key "pagetypeformats" can\'t be empty.');
×
255
        }
256
        if (!\is_array($formats)) {
1✔
257
            $formats = [$formats];
×
258
        }
259

260
        return $formats;
1✔
261
    }
262

263
    /**
264
     * Get alternates.
265
     */
266
    protected function getAlternates(array $formats): array
267
    {
268
        $alternates = [];
1✔
269

270
        if (\count($formats) > 1 || \in_array('html', $formats)) {
1✔
271
            foreach ($formats as $format) {
1✔
272
                $format == 'html' ? $rel = 'canonical' : $rel = 'alternate';
1✔
273
                $alternates[] = [
1✔
274
                    'rel'    => $rel,
1✔
275
                    'type'   => $this->config->getOutputFormatProperty($format, 'mediatype'),
1✔
276
                    'title'  => strtoupper($format),
1✔
277
                    'format' => $format,
1✔
278
                ];
1✔
279
            }
280
        }
281

282
        return $alternates;
1✔
283
    }
284

285
    /**
286
     * Returns the collection of translated pages for a given page.
287
     */
288
    protected function getTranslations(Page $refPage): \Cecil\Collection\Page\Collection
289
    {
290
        $pages = $this->builder->getPages()->filter(function (Page $page) use ($refPage) {
1✔
291
            return $page->getId() !== $refPage->getId()
1✔
292
                && $page->getVariable('langref') == $refPage->getVariable('langref')
1✔
293
                && $page->getType() == $refPage->getType()
1✔
294
                && !empty($page->getVariable('published'))
1✔
295
                && !$page->getVariable('paginated');
1✔
296
        });
1✔
297

298
        return $pages;
1✔
299
    }
300
}
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