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

Cecilapp / Cecil / 15736781440

18 Jun 2025 03:15PM UTC coverage: 82.623% (+0.01%) from 82.609%
15736781440

push

github

ArnaudLigny
refactor: better code

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

6 existing lines in 1 file now uncovered.

3119 of 3775 relevant lines covered (82.62%)

0.83 hits per line

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

91.09
/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✔
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<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✔
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->getConfig()->get('theme') as $theme) {
1✔
364
            $this->getConfig()->import(
1✔
365
                Config::loadFile(Util::joinFile($this->getConfig()->getThemesPath(), $theme, 'config.yml'), true),
1✔
366
                Config::PRESERVE
1✔
367
            );
1✔
368
        }
369
    }
370

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

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

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

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

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

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

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

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

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

441
        return $this->data;
1✔
442
    }
443

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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