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

Cecilapp / Cecil / 5046064611

pending completion
5046064611

push

github

GitHub
perf: native_function_invocation (#1697)

322 of 322 new or added lines in 62 files covered. (100.0%)

2784 of 4121 relevant lines covered (67.56%)

0.68 hits per line

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

90.48
/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\Collection\Page\PrefixSuffix;
20
use Cecil\Exception\RuntimeException;
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
        /** @var Page $page */
89
        foreach ($pages as $page) {
1✔
90
            $count++;
1✔
91
            $rendered = [];
1✔
92

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

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

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

121
            // renders each output format
122
            foreach ($formats as $format) {
1✔
123
                // search for the template
124
                $layout = Layout::finder($page, $format, $this->config);
1✔
125
                // renders with Twig
126
                try {
127
                    $deprecations = [];
1✔
128
                    set_error_handler(function ($type, $msg) use (&$deprecations) {
1✔
129
                        if (E_USER_DEPRECATED === $type) {
1✔
130
                            $deprecations[] = $msg;
1✔
131
                        }
132
                    });
1✔
133
                    $output = $this->builder->getRenderer()->render($layout['file'], ['page' => $page]);
1✔
134
                    foreach ($deprecations as $value) {
1✔
135
                        $this->builder->getLogger()->warning($value);
1✔
136
                    }
137
                    $output = $this->postProcessOutput($output, $page, $format);
1✔
138
                    $rendered[$format] = [
1✔
139
                        'output'   => $output,
1✔
140
                        'template' => [
1✔
141
                            'scope' => $layout['scope'],
1✔
142
                            'file'  => $layout['file'],
1✔
143
                        ]
1✔
144
                    ];
1✔
145
                    $page->addRendered($rendered);
1✔
146
                    // profiler
147
                    if ($this->builder->isDebug()) {
1✔
148
                        $dumper = new \Twig\Profiler\Dumper\HtmlDumper();
1✔
149
                        file_put_contents(
1✔
150
                            Util::joinFile($this->config->getOutputPath(), '_debug_twig_profile.html'),
1✔
151
                            $dumper->dump($this->builder->getRenderer()->getDebugProfile())
1✔
152
                        );
1✔
153
                    }
154
                } catch (\Twig\Error\Error $e) {
×
155
                    $template = !empty($e->getSourceContext()->getPath()) ? $e->getSourceContext()->getPath() : $e->getSourceContext()->getName();
×
156

157
                    throw new RuntimeException(sprintf(
×
158
                        'Template "%s%s" (page: %s): %s',
×
159
                        $template,
×
160
                        $e->getTemplateLine() >= 0 ? sprintf(':%s', $e->getTemplateLine()) : '',
×
161
                        $page->getId(),
×
162
                        $e->getMessage()
×
163
                    ));
×
164
                }
165
            }
166
            $this->builder->getPages()->replace($page->getId(), $page);
1✔
167

168
            $templates = array_column($rendered, 'template');
1✔
169
            $message = sprintf(
1✔
170
                'Page "%s" rendered with [%s]',
1✔
171
                ($page->getId() ?: 'index'),
1✔
172
                Util\Str::combineArrayToString($templates, 'scope', 'file')
1✔
173
            );
1✔
174
            $this->builder->getLogger()->info($message, ['progress' => [$count, $total]]);
1✔
175
        }
176
    }
177

178
    /**
179
     * Returns an array of layouts directories.
180
     */
181
    protected function getAllLayoutsPaths(): array
182
    {
183
        $paths = [];
1✔
184

185
        // layouts/
186
        if (is_dir($this->config->getLayoutsPath())) {
1✔
187
            $paths[] = $this->config->getLayoutsPath();
1✔
188
        }
189
        // <theme>/layouts/
190
        if ($this->config->hasTheme()) {
1✔
191
            $themes = $this->config->getTheme();
1✔
192
            foreach ($themes as $theme) {
1✔
193
                $paths[] = $this->config->getThemeDirPath($theme);
1✔
194
            }
195
        }
196
        // resources/layouts/
197
        if (is_dir($this->config->getInternalLayoutsPath())) {
1✔
198
            $paths[] = $this->config->getInternalLayoutsPath();
1✔
199
        }
200

201
        return $paths;
1✔
202
    }
203

204
    /**
205
     * Adds global variables.
206
     */
207
    protected function addGlobals()
208
    {
209
        $this->builder->getRenderer()->addGlobal('cecil', [
1✔
210
            'url'       => sprintf('https://cecil.app/#%s', Builder::getVersion()),
1✔
211
            'version'   => Builder::getVersion(),
1✔
212
            'poweredby' => sprintf('Cecil v%s', Builder::getVersion()),
1✔
213
        ]);
1✔
214
    }
215

216
    /**
217
     * Get available output formats.
218
     *
219
     * @throws RuntimeException
220
     */
221
    protected function getOutputFormats(Page $page): array
222
    {
223
        // Get page output format(s) if defined.
224
        // ie:
225
        // ```yaml
226
        // output: txt
227
        // ```
228
        if ($page->getVariable('output')) {
1✔
229
            $formats = $page->getVariable('output');
1✔
230
            if (!\is_array($formats)) {
1✔
231
                $formats = [$formats];
1✔
232
            }
233

234
            return $formats;
1✔
235
        }
236

237
        // Get available output formats for the page type.
238
        // ie:
239
        // ```yaml
240
        // page: [html, json]
241
        // ```
242
        $formats = $this->config->get('output.pagetypeformats.' . $page->getType());
1✔
243
        if (empty($formats)) {
1✔
244
            throw new RuntimeException('Configuration key "pagetypeformats" can\'t be empty.');
×
245
        }
246
        if (!\is_array($formats)) {
1✔
247
            $formats = [$formats];
×
248
        }
249

250
        return $formats;
1✔
251
    }
252

253
    /**
254
     * Get alternates.
255
     */
256
    protected function getAlternates(array $formats): array
257
    {
258
        $alternates = [];
1✔
259

260
        if (\count($formats) > 1 || \in_array('html', $formats)) {
1✔
261
            foreach ($formats as $format) {
1✔
262
                $format == 'html' ? $rel = 'canonical' : $rel = 'alternate';
1✔
263
                $alternates[] = [
1✔
264
                    'rel'    => $rel,
1✔
265
                    'type'   => $this->config->getOutputFormatProperty($format, 'mediatype'),
1✔
266
                    'title'  => strtoupper($format),
1✔
267
                    'format' => $format,
1✔
268
                ];
1✔
269
            }
270
        }
271

272
        return $alternates;
1✔
273
    }
274

275
    /**
276
     * Returns the collection of translated pages for a given page.
277
     */
278
    protected function getTranslations(Page $refPage): \Cecil\Collection\Page\Collection
279
    {
280
        $pages = $this->builder->getPages()->filter(function (Page $page) use ($refPage) {
1✔
281
            return $page->getId() !== $refPage->getId()
1✔
282
                && $page->getVariable('langref') == $refPage->getVariable('langref')
1✔
283
                && $page->getType() == $refPage->getType()
1✔
284
                && !empty($page->getVariable('published'))
1✔
285
                && !$page->getVariable('paginated');
1✔
286
        });
1✔
287

288
        return $pages;
1✔
289
    }
290

291
    /**
292
     * Apply post rendering on output.
293
     */
294
    private function postProcessOutput(string $output, Page $page, string $format): string
295
    {
296
        switch ($format) {
297
            case 'html':
1✔
298
                // add generator meta tag
299
                if (!preg_match('/<meta name="generator".*/i', $output)) {
1✔
300
                    $meta = sprintf('<meta name="generator" content="Cecil %s" />', Builder::getVersion());
1✔
301
                    $output = preg_replace_callback('/([[:blank:]]*)(<\/head>)/i', function ($matches) use ($meta) {
1✔
302
                        return str_repeat($matches[1] ?: ' ', 2) . $meta . "\n" . $matches[1] . $matches[2];
1✔
303
                    }, $output);
1✔
304
                }
305
                // replace excerpt or break tag by HTML anchor
306
                // https://regex101.com/r/Xl7d5I/3
307
                $pattern = '(.*)(<!--[[:blank:]]?(excerpt|break)[[:blank:]]?-->)(.*)';
1✔
308
                $replacement = '$1<span id="more"></span>$4';
1✔
309
                $excerpt = preg_replace('/' . $pattern . '/is', $replacement, $output, 1);
1✔
310
                $output = $excerpt ?? $output;
1✔
311
        }
312

313
        // replace internal link to *.md files with the right URL
314
        $output = preg_replace_callback(
1✔
315
            // https://regex101.com/r/ycWMe4/1
316
            '/href="(\/|)([A-Za-z0-9_\.\-\/]+)\.md(\#[A-Za-z0-9_\-]+)?"/is',
1✔
317
            function ($matches) use ($page) {
1✔
318
                // section spage
319
                $hrefPattern = 'href="../%s/%s"';
1✔
320
                // root page
321
                if (empty($page->getFolder())) {
1✔
322
                    $hrefPattern = 'href="%s/%s"';
1✔
323
                }
324
                // root link
325
                if ($matches[1] == '/') {
1✔
326
                    $hrefPattern = 'href="/%s/%s"';
1✔
327
                }
328

329
                return sprintf($hrefPattern, Page::slugify(PrefixSuffix::sub($matches[2])), $matches[3] ?? '');
1✔
330
            },
1✔
331
            $output
1✔
332
        );
1✔
333

334
        return $output;
1✔
335
    }
336
}
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