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

Cecilapp / Cecil / 13307084916

13 Feb 2025 11:53AM UTC coverage: 83.409%. First build
13307084916

Pull #2117

github

web-flow
Merge 677a5f516 into 6dbf9efc0
Pull Request #2117: refactor: better log/console messages

2 of 7 new or added lines in 4 files covered. (28.57%)

2951 of 3538 relevant lines covered (83.41%)

0.83 hits per line

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

89.55
/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✔
NEW
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
        $postprocessors = [];
1✔
89
        foreach ($this->config->get('output.postprocessors') as $name => $postprocessor) {
1✔
90
            try {
91
                if (!class_exists($postprocessor)) {
1✔
92
                    throw new RuntimeException(\sprintf('Class "%s" not found', $postprocessor));
1✔
93
                }
94
                $postprocessors[] = new $postprocessor($this->builder);
1✔
95
                $this->builder->getLogger()->debug(\sprintf('Output post processor "%s" loaded', $name));
1✔
96
            } catch (\Exception $e) {
1✔
97
                $this->builder->getLogger()->error(\sprintf('Unable to load output post processor "%s": %s', $name, $e->getMessage()));
1✔
98
            }
99
        }
100
        /** @var Page $page */
101
        foreach ($pages as $page) {
1✔
102
            $count++;
1✔
103
            $rendered = [];
1✔
104

105
            // l10n
106
            $language = $page->getVariable('language', $this->config->getLanguageDefault());
1✔
107
            $locale = $this->config->getLanguageProperty('locale', $language);
1✔
108
            $this->builder->getRenderer()->setLocale($locale);
1✔
109

110
            // global site variables
111
            $this->builder->getRenderer()->addGlobal('site', new Site($this->builder, $language));
1✔
112

113
            // global config raw variables
114
            $this->builder->getRenderer()->addGlobal('config', new Config($this->builder, $language));
1✔
115

116
            // excluded format(s)?
117
            $formats = (array) $page->getVariable('output');
1✔
118
            foreach ($formats as $key => $format) {
1✔
119
                if ($exclude = $this->config->getOutputFormatProperty($format, 'exclude')) {
1✔
120
                    // ie:
121
                    //   formats:
122
                    //     atom:
123
                    //       [...]
124
                    //       exclude: [paginated]
125
                    if (!\is_array($exclude)) {
1✔
126
                        $exclude = [$exclude];
×
127
                    }
128
                    foreach ($exclude as $variable) {
1✔
129
                        if ($page->hasVariable($variable)) {
1✔
130
                            unset($formats[$key]);
1✔
131
                        }
132
                    }
133
                }
134
            }
135

136
            // renders each output format
137
            foreach ($formats as $format) {
1✔
138
                // search for the template
139
                $layout = Layout::finder($page, $format, $this->config);
1✔
140
                // renders with Twig
141
                try {
142
                    $deprecations = [];
1✔
143
                    set_error_handler(function ($type, $msg) use (&$deprecations) {
1✔
144
                        if (E_USER_DEPRECATED === $type) {
1✔
145
                            $deprecations[] = $msg;
1✔
146
                        }
147
                    });
1✔
148
                    $output = $this->builder->getRenderer()->render($layout['file'], ['page' => $page]);
1✔
149
                    foreach ($deprecations as $value) {
1✔
150
                        $this->builder->getLogger()->warning($value);
1✔
151
                    }
152
                    foreach ($postprocessors as $postprocessor) {
1✔
153
                        $output = $postprocessor->process($page, $output, $format);
1✔
154
                    }
155
                    $rendered[$format] = [
1✔
156
                        'output'   => $output,
1✔
157
                        'template' => [
1✔
158
                            'scope' => $layout['scope'],
1✔
159
                            'file'  => $layout['file'],
1✔
160
                        ],
1✔
161
                    ];
1✔
162
                    $page->addRendered($rendered);
1✔
163
                    // profiler
164
                    if ($this->builder->isDebug()) {
1✔
165
                        $dumper = new \Twig\Profiler\Dumper\HtmlDumper();
1✔
166
                        file_put_contents(
1✔
167
                            Util::joinFile($this->config->getOutputPath(), '_debug_twig_profile.html'),
1✔
168
                            $dumper->dump($this->builder->getRenderer()->getDebugProfile())
1✔
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
            $this->builder->getPages()->replace($page->getId(), $page);
1✔
184

185
            $templates = array_column($rendered, 'template');
1✔
186
            $message = \sprintf(
1✔
187
                'Page "%s" rendered with [%s]',
1✔
188
                $page->getId() ?: 'index',
1✔
189
                Util\Str::combineArrayToString($templates, 'scope', 'file')
1✔
190
            );
1✔
191
            $this->builder->getLogger()->info($message, ['progress' => [$count, $total]]);
1✔
192
        }
193
    }
194

195
    /**
196
     * Returns an array of layouts directories.
197
     */
198
    protected function getAllLayoutsPaths(): array
199
    {
200
        $paths = [];
1✔
201

202
        // layouts/
203
        if (is_dir($this->config->getLayoutsPath())) {
1✔
204
            $paths[] = $this->config->getLayoutsPath();
1✔
205
        }
206
        // <theme>/layouts/
207
        if ($this->config->hasTheme()) {
1✔
208
            $themes = $this->config->getTheme();
1✔
209
            foreach ($themes as $theme) {
1✔
210
                $paths[] = $this->config->getThemeDirPath($theme);
1✔
211
            }
212
        }
213
        // resources/layouts/
214
        if (is_dir($this->config->getLayoutsInternalPath())) {
1✔
215
            $paths[] = $this->config->getLayoutsInternalPath();
1✔
216
        }
217

218
        return $paths;
1✔
219
    }
220

221
    /**
222
     * Adds global variables.
223
     */
224
    protected function addGlobals()
225
    {
226
        $this->builder->getRenderer()->addGlobal('cecil', [
1✔
227
            'url'       => \sprintf('https://cecil.app/#%s', Builder::getVersion()),
1✔
228
            'version'   => Builder::getVersion(),
1✔
229
            'poweredby' => \sprintf('Cecil v%s', Builder::getVersion()),
1✔
230
        ]);
1✔
231
    }
232

233
    /**
234
     * Get available output formats.
235
     *
236
     * @throws RuntimeException
237
     */
238
    protected function getOutputFormats(Page $page): array
239
    {
240
        // Get page output format(s) if defined.
241
        // ie:
242
        // ```yaml
243
        // output: txt
244
        // ```
245
        if ($page->getVariable('output')) {
1✔
246
            $formats = $page->getVariable('output');
1✔
247
            if (!\is_array($formats)) {
1✔
248
                $formats = [$formats];
1✔
249
            }
250

251
            return $formats;
1✔
252
        }
253

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

267
        return array_unique($formats);
1✔
268
    }
269

270
    /**
271
     * Get alternates.
272
     */
273
    protected function getAlternates(array $formats): array
274
    {
275
        $alternates = [];
1✔
276

277
        if (\count($formats) > 1 || \in_array('html', $formats)) {
1✔
278
            foreach ($formats as $format) {
1✔
279
                $format == 'html' ? $rel = 'canonical' : $rel = 'alternate';
1✔
280
                $alternates[] = [
1✔
281
                    'rel'    => $rel,
1✔
282
                    'type'   => $this->config->getOutputFormatProperty($format, 'mediatype'),
1✔
283
                    'title'  => strtoupper($format),
1✔
284
                    'format' => $format,
1✔
285
                ];
1✔
286
            }
287
        }
288

289
        return $alternates;
1✔
290
    }
291

292
    /**
293
     * Returns the collection of translated pages for a given page.
294
     */
295
    protected function getTranslations(Page $refPage): \Cecil\Collection\Page\Collection
296
    {
297
        $pages = $this->builder->getPages()->filter(function (Page $page) use ($refPage) {
1✔
298
            return $page->getId() !== $refPage->getId()
1✔
299
                && $page->getVariable('langref') == $refPage->getVariable('langref')
1✔
300
                && $page->getType() == $refPage->getType()
1✔
301
                && !empty($page->getVariable('published'))
1✔
302
                && !$page->getVariable('paginated');
1✔
303
        });
1✔
304

305
        return $pages;
1✔
306
    }
307
}
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