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

Cecilapp / Cecil / 15735686664

18 Jun 2025 02:29PM UTC coverage: 82.609% (-0.02%) from 82.627%
15735686664

push

github

ArnaudLigny
refactor: code quality

0 of 1 new or added line in 1 file covered. (0.0%)

79 existing lines in 5 files now uncovered.

3116 of 3772 relevant lines covered (82.61%)

0.83 hits per line

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

90.82
/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
class Builder implements LoggerAwareInterface
33
{
34
    public const VERSION = '8.x-dev';
35
    public const VERBOSITY_QUIET = -1;
36
    public const VERBOSITY_NORMAL = 0;
37
    public const VERBOSITY_VERBOSE = 1;
38
    public const VERBOSITY_DEBUG = 2;
39
    /**
40
     * Default options for the build process.
41
     * These options can be overridden when calling the build() method.
42
     * - 'drafts': if true, builds drafts too (default: false)
43
     * - 'dry-run': if true, generated files are not saved (default: false)
44
     * - 'page': if specified, only this page is processed (default: '')
45
     * - 'render-subset': limits the render step to a specific subset (default: '')
46
     * @var array<string, bool|string>
47
     * @see \Cecil\Builder::build()
48
     */
49
    public const OPTIONS = [
50
        'drafts'  => false,
51
        'dry-run' => false,
52
        'page'    => '',
53
        'render-subset' => '',
54
    ];
55

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

201
    /**
202
     * @param Config|array|null    $config
203
     * @param LoggerInterface|null $logger
204
     */
205
    public function __construct($config = null, ?LoggerInterface $logger = null)
206
    {
207
        // init and set config
208
        $this->config = new Config();
1✔
209
        if ($config !== null) {
1✔
210
            $this->setConfig($config);
1✔
211
        }
212
        // debug mode?
213
        if (getenv('CECIL_DEBUG') == 'true' || $this->getConfig()->isEnabled('debug')) {
1✔
214
            $this->debug = true;
1✔
215
        }
216
        // set logger
217
        if ($logger === null) {
1✔
UNCOV
218
            $logger = new PrintLogger(self::VERBOSITY_VERBOSE);
×
219
        }
220
        $this->setLogger($logger);
1✔
221
    }
222

223
    /**
224
     * Creates a new Builder instance.
225
     */
226
    public static function create(): self
227
    {
228
        $class = new \ReflectionClass(\get_called_class());
1✔
229

230
        return $class->newInstanceArgs(\func_get_args());
1✔
231
    }
232

233
    /**
234
     * Builds a new website.
235
     * This method processes the build steps in order, collects content, data, static files,
236
     * generates pages, renders them, and saves the output to the destination directory.
237
     * It also collects metrics about the build process, such as duration and memory usage.
238
     * @param array<string, self::OPTIONS> $options
239
     * @see \Cecil\Builder::OPTIONS
240
     */
241
    public function build(array $options): self
242
    {
243
        // set start script time and memory usage
244
        $startTime = microtime(true);
1✔
245
        $startMemory = memory_get_usage();
1✔
246

247
        // checks soft errors
248
        $this->checkErrors();
1✔
249

250
        // merge options with defaults
251
        $this->options = array_merge(self::OPTIONS, $options);
1✔
252

253
        // set build ID
254
        $this->buildId = date('YmdHis');
1✔
255

256
        // process each step
257
        $steps = [];
1✔
258
        // init...
259
        foreach ($this->steps as $step) {
1✔
260
            /** @var Step\StepInterface $stepObject */
261
            $stepObject = new $step($this);
1✔
262
            $stepObject->init($this->options);
1✔
263
            if ($stepObject->canProcess()) {
1✔
264
                $steps[] = $stepObject;
1✔
265
            }
266
        }
267
        // ...and process
268
        $stepNumber = 0;
1✔
269
        $stepsTotal = \count($steps);
1✔
270
        foreach ($steps as $step) {
1✔
271
            $stepNumber++;
1✔
272
            /** @var Step\StepInterface $step */
273
            $this->getLogger()->notice($step->getName(), ['step' => [$stepNumber, $stepsTotal]]);
1✔
274
            $stepStartTime = microtime(true);
1✔
275
            $stepStartMemory = memory_get_usage();
1✔
276
            $step->process();
1✔
277
            // step duration and memory usage
278
            $this->metrics['steps'][$stepNumber]['name'] = $step->getName();
1✔
279
            $this->metrics['steps'][$stepNumber]['duration'] = Util::convertMicrotime((float) $stepStartTime);
1✔
280
            $this->metrics['steps'][$stepNumber]['memory']   = Util::convertMemory(memory_get_usage() - $stepStartMemory);
1✔
281
            $this->getLogger()->info(\sprintf(
1✔
282
                '%s done in %s (%s)',
1✔
283
                $this->metrics['steps'][$stepNumber]['name'],
1✔
284
                $this->metrics['steps'][$stepNumber]['duration'],
1✔
285
                $this->metrics['steps'][$stepNumber]['memory']
1✔
286
            ));
1✔
287
        }
288
        // build duration and memory usage
289
        $this->metrics['total']['duration'] = Util::convertMicrotime($startTime);
1✔
290
        $this->metrics['total']['memory']   = Util::convertMemory(memory_get_usage() - $startMemory);
1✔
291
        $this->getLogger()->notice(\sprintf('Built in %s (%s)', $this->metrics['total']['duration'], $this->metrics['total']['memory']));
1✔
292

293
        return $this;
1✔
294
    }
295

296
    /**
297
     * Returns current build ID.
298
     */
299
    public function getBuildId(): string
300
    {
301
        return $this->buildId;
1✔
302
    }
303

304
    /**
305
     * Set configuration.
306
     */
307
    public function setConfig(array|Config $config): self
308
    {
309
        if (\is_array($config)) {
1✔
310
            $config = new Config($config);
1✔
311
        }
312
        if ($this->config !== $config) {
1✔
313
            $this->config = $config;
1✔
314
        }
315

316
        // import themes configuration
317
        $this->importThemesConfig();
1✔
318
        // autoloads local extensions
319
        Util::autoload($this, 'extensions');
1✔
320

321
        return $this;
1✔
322
    }
323

324
    /**
325
     * Returns configuration.
326
     */
327
    public function getConfig(): Config
328
    {
329
        if ($this->config === null) {
1✔
UNCOV
330
            $this->config = new Config();
×
331
        }
332

333
        return $this->config;
1✔
334
    }
335

336
    /**
337
     * Config::setSourceDir() alias.
338
     */
339
    public function setSourceDir(string $sourceDir): self
340
    {
341
        $this->getConfig()->setSourceDir($sourceDir);
1✔
342
        // import themes configuration
343
        $this->importThemesConfig();
1✔
344

345
        return $this;
1✔
346
    }
347

348
    /**
349
     * Config::setDestinationDir() alias.
350
     */
351
    public function setDestinationDir(string $destinationDir): self
352
    {
353
        $this->getConfig()->setDestinationDir($destinationDir);
1✔
354

355
        return $this;
1✔
356
    }
357

358
    /**
359
     * Import themes configuration.
360
     */
361
    public function importThemesConfig(): void
362
    {
363
        foreach ((array) $this->config->get('theme') as $theme) {
1✔
364
            $this->config->import(Config::loadFile(Util::joinFile($this->config->getThemesPath(), $theme, 'config.yml'), true), Config::PRESERVE);
1✔
365
        }
366
    }
367

368
    /**
369
     * {@inheritdoc}
370
     */
371
    public function setLogger(LoggerInterface $logger): void
372
    {
373
        $this->logger = $logger;
1✔
374
    }
375

376
    /**
377
     * Returns the logger instance.
378
     */
379
    public function getLogger(): LoggerInterface
380
    {
381
        return $this->logger;
1✔
382
    }
383

384
    /**
385
     * Returns debug mode state.
386
     */
387
    public function isDebug(): bool
388
    {
389
        return (bool) $this->debug;
1✔
390
    }
391

392
    /**
393
     * Returns build options.
394
     */
395
    public function getBuildOptions(): array
396
    {
397
        return $this->options;
1✔
398
    }
399

400
    /**
401
     * Set collected pages files.
402
     */
403
    public function setPagesFiles(Finder $content): void
404
    {
405
        $this->content = $content;
1✔
406
    }
407

408
    /**
409
     * Returns pages files.
410
     */
411
    public function getPagesFiles(): ?Finder
412
    {
413
        return $this->content;
1✔
414
    }
415

416
    /**
417
     * Set collected data.
418
     */
419
    public function setData(array $data): void
420
    {
421
        $this->data = $data;
1✔
422
    }
423

424
    /**
425
     * Returns data collection.
426
     */
427
    public function getData(?string $language = null): array
428
    {
429
        if ($language) {
1✔
430
            if (empty($this->data[$language])) {
1✔
431
                // fallback to default language
432
                return $this->data[$this->config->getLanguageDefault()];
1✔
433
            }
434

435
            return $this->data[$language];
1✔
436
        }
437

438
        return $this->data;
1✔
439
    }
440

441
    /**
442
     * Set collected static files.
443
     */
444
    public function setStatic(array $static): void
445
    {
446
        $this->static = $static;
1✔
447
    }
448

449
    /**
450
     * Returns static files collection.
451
     */
452
    public function getStatic(): array
453
    {
454
        return $this->static;
1✔
455
    }
456

457
    /**
458
     * Set/update Pages collection.
459
     */
460
    public function setPages(PagesCollection $pages): void
461
    {
462
        $this->pages = $pages;
1✔
463
    }
464

465
    /**
466
     * Returns pages collection.
467
     */
468
    public function getPages(): ?PagesCollection
469
    {
470
        return $this->pages;
1✔
471
    }
472

473
    /**
474
     * Set assets path list.
475
     */
476
    public function setAssets(array $assets): void
477
    {
UNCOV
478
        $this->assets = $assets;
×
479
    }
480

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

491
    /**
492
     * Returns list of assets path.
493
     */
494
    public function getAssets(): array
495
    {
496
        return $this->assets;
1✔
497
    }
498

499
    /**
500
     * Set menus collection.
501
     */
502
    public function setMenus(array $menus): void
503
    {
504
        $this->menus = $menus;
1✔
505
    }
506

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

515
    /**
516
     * Set taxonomies collection.
517
     */
518
    public function setTaxonomies(array $taxonomies): void
519
    {
520
        $this->taxonomies = $taxonomies;
1✔
521
    }
522

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

531
    /**
532
     * Set renderer object.
533
     */
534
    public function setRenderer(Renderer\RendererInterface $renderer): void
535
    {
536
        $this->renderer = $renderer;
1✔
537
    }
538

539
    /**
540
     * Returns Renderer object.
541
     */
542
    public function getRenderer(): Renderer\RendererInterface
543
    {
544
        return $this->renderer;
1✔
545
    }
546

547
    /**
548
     * Returns metrics array.
549
     */
550
    public function getMetrics(): array
551
    {
UNCOV
552
        return $this->metrics;
×
553
    }
554

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

575
        return self::$version;
1✔
576
    }
577

578
    /**
579
     * Log soft errors.
580
     */
581
    protected function checkErrors(): void
582
    {
583
        // baseurl is required in production
584
        if (empty(trim((string) $this->config->get('baseurl'), '/'))) {
1✔
UNCOV
585
            $this->getLogger()->error('`baseurl` configuration key is required in production.');
×
586
        }
587
    }
588
}
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