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

Cecilapp / Cecil / 23439981062

23 Mar 2026 01:34PM UTC coverage: 82.395%. First build
23439981062

Pull #2333

github

web-flow
Merge 7227d073f into 506382a9c
Pull Request #2333: feat: add raw timings, diffs and save metrics

9 of 10 new or added lines in 1 file covered. (90.0%)

3323 of 4033 relevant lines covered (82.4%)

0.82 hits per line

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

91.67
/src/Builder.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;
15

16
use Cecil\Collection\Page\Collection as PagesCollection;
17
use Cecil\Exception\RuntimeException;
18
use Cecil\Generator\GeneratorManager;
19
use Cecil\Logger\PrintLogger;
20
use Psr\Log\LoggerAwareInterface;
21
use Psr\Log\LoggerInterface;
22
use Symfony\Component\Finder\Finder;
23

24
/**
25
 * The main Cecil builder class.
26
 *
27
 * This class is responsible for building the website by processing various steps,
28
 * managing configuration, and handling content, data, static files, pages, assets,
29
 * menus, taxonomies, and rendering.
30
 * It also provides methods for logging, debugging, and managing build metrics.
31
 *
32
 * ```php
33
 * $config = [
34
 *   'title'   => "My website",
35
 *   'baseurl' => 'https://domain.tld/',
36
 * ];
37
 * Builder::create($config)->build();
38
 * ```
39
 */
40
class Builder implements LoggerAwareInterface
41
{
42
    public const VERSION = '8.x-dev';
43
    public const VERBOSITY_QUIET = -1;
44
    public const VERBOSITY_NORMAL = 0;
45
    public const VERBOSITY_VERBOSE = 1;
46
    public const VERBOSITY_DEBUG = 2;
47
    /**
48
     * Default options for the build process.
49
     * These options can be overridden when calling the build() method.
50
     * - 'drafts': if true, builds drafts too (default: false)
51
     * - 'dry-run': if true, generated files are not saved (default: false)
52
     * - 'page': if specified, only this page is processed (default: '')
53
     * - 'render-subset': limits the render step to a specific subset (default: '')
54
     * @var array<string, bool|string>
55
     * @see \Cecil\Builder::build()
56
     */
57
    public const OPTIONS = [
58
        'drafts'  => false,
59
        'dry-run' => false,
60
        'page'    => '',
61
        'render-subset' => '',
62
    ];
63
    /**
64
     * Steps processed by build(), in order.
65
     * These steps are executed sequentially to build the website.
66
     * Each step is a class that implements the StepInterface.
67
     * @var array<string>
68
     * @see \Cecil\Step\StepInterface
69
     */
70
    public const STEPS = [
71
        'Cecil\Step\Pages\Load',
72
        'Cecil\Step\Data\Load',
73
        'Cecil\Step\StaticFiles\Load',
74
        'Cecil\Step\Pages\Create',
75
        'Cecil\Step\Pages\Convert',
76
        'Cecil\Step\Taxonomies\Create',
77
        'Cecil\Step\Pages\Generate',
78
        'Cecil\Step\Menus\Create',
79
        'Cecil\Step\StaticFiles\Copy',
80
        'Cecil\Step\Pages\Render',
81
        'Cecil\Step\Pages\Save',
82
        'Cecil\Step\Assets\Save',
83
        'Cecil\Step\Optimize\Html',
84
        'Cecil\Step\Optimize\Css',
85
        'Cecil\Step\Optimize\Js',
86
        'Cecil\Step\Optimize\Images',
87
    ];
88
    /**
89
     * Temporary directory name.
90
     */
91
    public const TMP_DIR = '.cecil';
92

93
    /**
94
     * Configuration object.
95
     * This object holds all the configuration settings for the build process.
96
     * It can be set to an array or a Config instance.
97
     * @var Config|array|null
98
     * @see \Cecil\Config
99
     */
100
    protected $config;
101
    /**
102
     * Logger instance.
103
     * This logger is used to log messages during the build process.
104
     * It can be set to any PSR-3 compliant logger.
105
     * @var LoggerInterface
106
     * @see \Psr\Log\LoggerInterface
107
     * */
108
    protected $logger;
109
    /**
110
     * Debug mode state.
111
     * If true, debug messages are logged.
112
     * @var bool
113
     */
114
    protected $debug = false;
115
    /**
116
     * Build options.
117
     * These options can be passed to the build() method to customize the build process.
118
     * @var array
119
     * @see \Cecil\Builder::OPTIONS
120
     * @see \Cecil\Builder::build()
121
     */
122
    protected $options = [];
123
    /**
124
     * Content files collection.
125
     * This is a Finder instance that collects all the content files (pages, posts, etc.) from the source directory.
126
     * @var Finder
127
     */
128
    protected $content;
129
    /**
130
     * Data collection.
131
     * This is an associative array that holds data loaded from YAML files in the data directory.
132
     * @var array
133
     */
134
    protected $data = [];
135
    /**
136
     * Static files collection.
137
     * This is an associative array that holds static files (like images, CSS, JS) that are copied to the destination directory.
138
     * @var array
139
     */
140
    protected $static = [];
141
    /**
142
     * Pages collection.
143
     * This is a collection of pages that have been processed and are ready for rendering.
144
     * It is an instance of PagesCollection, which is a custom collection class for managing pages.
145
     * @var PagesCollection
146
     */
147
    protected $pages;
148
    /**
149
     * Assets path collection.
150
     * This is an array that holds paths to assets (like CSS, JS, images) that are used in the build process.
151
     * It is used to keep track of assets that need to be processed or copied.
152
     * @var array
153
     */
154
    protected $assets = [];
155
    /**
156
     * Menus collection.
157
     * This is an associative array that holds menus for different languages.
158
     * Each key is a language code, and the value is a Collection\Menu\Collection instance
159
     * that contains the menu items for that language.
160
     * It is used to manage navigation menus across different languages in the website.
161
     * @var array
162
     * @see \Cecil\Collection\Menu\Collection
163
     */
164
    protected $menus;
165
    /**
166
     * Taxonomies collection.
167
     * This is an associative array that holds taxonomies for different languages.
168
     * Each key is a language code, and the value is a Collection\Taxonomy\Collection instance
169
     * that contains the taxonomy terms for that language.
170
     * It is used to manage taxonomies (like categories, tags) across different languages in the website.
171
     * @var array
172
     * @see \Cecil\Collection\Taxonomy\Collection
173
     */
174
    protected $taxonomies;
175
    /**
176
     * Renderer.
177
     * This is an instance of Renderer\Twig that is responsible for rendering pages.
178
     * It handles the rendering of templates and the application of data to those templates.
179
     * @var Renderer\Twig
180
     */
181
    protected $renderer;
182
    /**
183
     * Generators manager.
184
     * This is an instance of GeneratorManager that manages all the generators used in the build process.
185
     * Generators are used to create dynamic content or perform specific tasks during the build.
186
     * It allows for the registration and execution of various generators that can extend the functionality of the build process.
187
     * @var GeneratorManager
188
     */
189
    protected $generatorManager;
190
    /**
191
     * Build metrics.
192
     * This array holds metrics about the build process, such as duration and memory usage for each step.
193
     * It is used to track the performance of the build and can be useful for debugging and optimization.
194
     * @var array
195
     */
196
    protected $metrics = [];
197
    /**
198
     * Application version.
199
     * @var string
200
     */
201
    protected static $version;
202
    /**
203
     * Current build ID.
204
     * This is a unique identifier for the current build process.
205
     * It is generated based on the current date and time when the build starts.
206
     * It can be used to track builds, especially in environments where multiple builds may occur.
207
     * @var string
208
     * @see \Cecil\Builder::build()
209
     */
210
    protected static $buildId;
211

212
    /**
213
     * @param Config|array|null    $config
214
     * @param LoggerInterface|null $logger
215
     */
216
    public function __construct($config = null, ?LoggerInterface $logger = null)
217
    {
218
        // init and set config
219
        $this->config = new Config();
1✔
220
        if ($config !== null) {
1✔
221
            $this->setConfig($config);
1✔
222
        }
223
        // debug mode?
224
        if (getenv('CECIL_DEBUG') == 'true' || $this->getConfig()->isEnabled('debug')) {
1✔
225
            $this->debug = true;
1✔
226
        }
227
        // set logger
228
        if ($logger === null) {
1✔
229
            $logger = new PrintLogger(self::VERBOSITY_VERBOSE);
×
230
        }
231
        $this->setLogger($logger);
1✔
232
    }
233

234
    /**
235
     * Creates a new Builder instance.
236
     */
237
    public static function create(): self
238
    {
239
        $class = new \ReflectionClass(\get_called_class());
1✔
240

241
        return $class->newInstanceArgs(\func_get_args());
1✔
242
    }
243

244
    /**
245
     * Builds a new website.
246
     * This method processes the build steps in order, collects content, data, static files,
247
     * generates pages, renders them, and saves the output to the destination directory.
248
     * It also collects metrics about the build process, such as duration and memory usage.
249
     * @param array<self::OPTIONS> $options
250
     * @see \Cecil\Builder::OPTIONS
251
     */
252
    public function build(array $options): self
253
    {
254
        // set start script time and memory usage
255
        $startTime = microtime(true);
1✔
256
        $startMemory = memory_get_usage();
1✔
257

258
        // checks soft errors
259
        $this->checkErrors();
1✔
260

261
        // merge options with defaults
262
        $this->options = array_merge(self::OPTIONS, $options);
1✔
263

264
        // set build ID
265
        self::$buildId = hash('adler32', date('YmdHis') . self::$version);
1✔
266

267
        // process each step
268
        $steps = [];
1✔
269
        // init...
270
        foreach (self::STEPS as $step) {
1✔
271
            $stepObject = new $step($this);
1✔
272
            $stepObject->init($this->options);
1✔
273
            if ($stepObject->canProcess()) {
1✔
274
                $steps[] = $stepObject;
1✔
275
            }
276
        }
277
        // ...and process
278
        $stepNumber = 0;
1✔
279
        $stepsTotal = \count($steps);
1✔
280
        foreach ($steps as $step) {
1✔
281
            $stepNumber++;
1✔
282
            $this->getLogger()->notice($step->getName(), ['step' => [$stepNumber, $stepsTotal]]);
1✔
283
            $stepStartTime = microtime(true);
1✔
284
            $stepStartMemory = memory_get_usage();
1✔
285
            $step->process();
1✔
286
            // step duration and memory usage
287
            $stepDuration = microtime(true) - $stepStartTime;
1✔
288
            $this->metrics['steps'][$stepNumber]['name'] = $step->getName();
1✔
289
            $this->metrics['steps'][$stepNumber]['duration'] = $stepDuration < 1
1✔
290
                ? \sprintf('%s ms', round($stepDuration * 1000, 0))
1✔
291
                : \sprintf('%s s', round($stepDuration, 2));
1✔
292
            $this->metrics['steps'][$stepNumber]['duration_raw'] = round($stepDuration * 1000, 2);
1✔
293
            $this->metrics['steps'][$stepNumber]['memory']   = Util::convertMemory(memory_get_usage() - $stepStartMemory);
1✔
294
            $this->getLogger()->info(\sprintf(
1✔
295
                '%s done in %s (%s)',
1✔
296
                $this->metrics['steps'][$stepNumber]['name'],
1✔
297
                $this->metrics['steps'][$stepNumber]['duration'],
1✔
298
                $this->metrics['steps'][$stepNumber]['memory']
1✔
299
            ));
1✔
300
        }
301
        // build duration and memory usage
302
        $totalDuration = microtime(true) - $startTime;
1✔
303
        $this->metrics['total']['duration'] = $totalDuration < 1
1✔
NEW
304
            ? \sprintf('%s ms', round($totalDuration * 1000, 0))
×
305
            : \sprintf('%s s', round($totalDuration, 2));
1✔
306
        $this->metrics['total']['duration_raw'] = round($totalDuration * 1000, 2);
1✔
307
        $this->metrics['total']['memory']   = Util::convertMemory(memory_get_usage() - $startMemory);
1✔
308
        $this->getLogger()->notice(\sprintf('Built in %s (%s)', $this->metrics['total']['duration'], $this->metrics['total']['memory']));
1✔
309

310
        return $this;
1✔
311
    }
312

313
    /**
314
     * Set configuration.
315
     */
316
    public function setConfig(array|Config $config): self
317
    {
318
        if (\is_array($config)) {
1✔
319
            $config = new Config($config);
1✔
320
        }
321
        if ($this->config !== $config) {
1✔
322
            $this->config = $config;
1✔
323
        }
324

325
        // import themes configuration
326
        $this->importThemesConfig();
1✔
327
        // autoloads local extensions
328
        Util::autoload($this, 'extensions');
1✔
329

330
        return $this;
1✔
331
    }
332

333
    /**
334
     * Returns configuration.
335
     */
336
    public function getConfig(): Config
337
    {
338
        if ($this->config === null) {
1✔
339
            $this->config = new Config();
×
340
        }
341

342
        return $this->config;
1✔
343
    }
344

345
    /**
346
     * Config::setSourceDir() alias.
347
     */
348
    public function setSourceDir(string $sourceDir): self
349
    {
350
        $this->getConfig()->setSourceDir($sourceDir);
1✔
351
        // import themes configuration
352
        $this->importThemesConfig();
1✔
353

354
        return $this;
1✔
355
    }
356

357
    /**
358
     * Config::setDestinationDir() alias.
359
     */
360
    public function setDestinationDir(string $destinationDir): self
361
    {
362
        $this->getConfig()->setDestinationDir($destinationDir);
1✔
363

364
        return $this;
1✔
365
    }
366

367
    /**
368
     * Import themes configuration.
369
     */
370
    public function importThemesConfig(): void
371
    {
372
        foreach ((array) $this->getConfig()->get('theme') as $theme) {
1✔
373
            $this->getConfig()->import(
1✔
374
                Config::loadFile(Util::joinFile($this->getConfig()->getThemesPath(), $theme, 'config.yml'), true),
1✔
375
                Config::IMPORT_PRESERVE
1✔
376
            );
1✔
377
        }
378
    }
379

380
    /**
381
     * {@inheritdoc}
382
     */
383
    public function setLogger(LoggerInterface $logger): void
384
    {
385
        $this->logger = $logger;
1✔
386
    }
387

388
    /**
389
     * Returns the logger instance.
390
     */
391
    public function getLogger(): LoggerInterface
392
    {
393
        return $this->logger;
1✔
394
    }
395

396
    /**
397
     * Returns debug mode state.
398
     */
399
    public function isDebug(): bool
400
    {
401
        return (bool) $this->debug;
1✔
402
    }
403

404
    /**
405
     * Returns build options.
406
     */
407
    public function getBuildOptions(): array
408
    {
409
        return $this->options;
1✔
410
    }
411

412
    /**
413
     * Set collected pages files.
414
     */
415
    public function setPagesFiles(Finder $content): void
416
    {
417
        $this->content = $content;
1✔
418
    }
419

420
    /**
421
     * Returns pages files.
422
     */
423
    public function getPagesFiles(): ?Finder
424
    {
425
        return $this->content;
1✔
426
    }
427

428
    /**
429
     * Set collected data.
430
     */
431
    public function setData(array $data): void
432
    {
433
        $this->data = $data;
1✔
434
    }
435

436
    /**
437
     * Returns data collection.
438
     */
439
    public function getData(?string $language = null): array
440
    {
441
        if ($language) {
1✔
442
            if (empty($this->data[$language])) {
1✔
443
                // fallback to default language
444
                return $this->data[$this->getConfig()->getLanguageDefault()];
1✔
445
            }
446

447
            return $this->data[$language];
1✔
448
        }
449

450
        return $this->data;
1✔
451
    }
452

453
    /**
454
     * Set collected static files.
455
     */
456
    public function setStatic(array $static): void
457
    {
458
        $this->static = $static;
1✔
459
    }
460

461
    /**
462
     * Returns static files collection.
463
     */
464
    public function getStatic(): array
465
    {
466
        return $this->static;
1✔
467
    }
468

469
    /**
470
     * Set/update Pages collection.
471
     */
472
    public function setPages(PagesCollection $pages): void
473
    {
474
        $this->pages = $pages;
1✔
475
    }
476

477
    /**
478
     * Returns pages collection.
479
     */
480
    public function getPages(): ?PagesCollection
481
    {
482
        return $this->pages;
1✔
483
    }
484

485
    /**
486
     * Add an asset path to assets list.
487
     */
488
    public function addToAssetsList(string $path): void
489
    {
490
        if (!\in_array($path, $this->assets, true)) {
1✔
491
            $this->assets[] = $path;
1✔
492
        }
493
    }
494

495
    /**
496
     * Returns list of assets path.
497
     */
498
    public function getAssetsList(): array
499
    {
500
        return $this->assets;
1✔
501
    }
502

503
    /**
504
     * Set menus collection.
505
     */
506
    public function setMenus(array $menus): void
507
    {
508
        $this->menus = $menus;
1✔
509
    }
510

511
    /**
512
     * Returns all menus, for a language.
513
     */
514
    public function getMenus(string $language): Collection\Menu\Collection
515
    {
516
        return $this->menus[$language];
1✔
517
    }
518

519
    /**
520
     * Set taxonomies collection.
521
     */
522
    public function setTaxonomies(array $taxonomies): void
523
    {
524
        $this->taxonomies = $taxonomies;
1✔
525
    }
526

527
    /**
528
     * Returns taxonomies collection, for a language.
529
     */
530
    public function getTaxonomies(string $language): ?Collection\Taxonomy\Collection
531
    {
532
        return $this->taxonomies[$language];
1✔
533
    }
534

535
    /**
536
     * Set renderer object.
537
     */
538
    public function setRenderer(Renderer\Twig $renderer): void
539
    {
540
        $this->renderer = $renderer;
1✔
541
    }
542

543
    /**
544
     * Returns Renderer object.
545
     */
546
    public function getRenderer(): Renderer\Twig
547
    {
548
        return $this->renderer;
1✔
549
    }
550

551
    /**
552
     * Returns metrics array.
553
     */
554
    public function getMetrics(): array
555
    {
556
        return $this->metrics;
×
557
    }
558

559
    /**
560
     * Returns application version.
561
     *
562
     * @throws RuntimeException
563
     */
564
    public static function getVersion(): string
565
    {
566
        if (!isset(self::$version)) {
1✔
567
            try {
568
                $filePath = Util\File::getRealPath('VERSION');
1✔
569
                $version = Util\File::fileGetContents($filePath);
×
570
                if ($version === false) {
×
571
                    throw new RuntimeException(\sprintf('Unable to read content of "%s".', $filePath));
×
572
                }
573
                self::$version = trim($version);
×
574
            } catch (\Exception) {
1✔
575
                self::$version = self::VERSION;
1✔
576
            }
577
        }
578

579
        return self::$version;
1✔
580
    }
581

582
    /**
583
     * Returns current build ID.
584
     */
585
    public static function getBuildId(): string
586
    {
587
        return self::$buildId;
1✔
588
    }
589

590
    /**
591
     * Log soft errors.
592
     */
593
    protected function checkErrors(): void
594
    {
595
        // baseurl is required in production
596
        if (empty(trim((string) $this->getConfig()->get('baseurl'), '/'))) {
1✔
597
            $this->getLogger()->error('`baseurl` configuration key is required in production.');
×
598
        }
599
    }
600
}
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