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

Cecilapp / Cecil / 22045060359

15 Feb 2026 11:24PM UTC coverage: 82.509% (+0.1%) from 82.382%
22045060359

push

github

ArnaudLigny
Handle domain-only paths; fetch HTML via Asset

Set a default path ('-index.html') when buildPathFromUrl encounters a URL with no path so extension detection and path handling work for domain-only URLs. Use that path when computing the extension. Replace direct file_get_contents() usage in htmlImageFromWebsite with creating an Asset (ignore_missing) to fetch the page, log a warning and return null when the HTML asset is missing, and then extract the image from the asset content. Also uncomment the HTML image-from-URL example in the test fixture.

5 of 7 new or added lines in 2 files covered. (71.43%)

55 existing lines in 2 files now uncovered.

3321 of 4025 relevant lines covered (82.51%)

0.83 hits per line

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

92.0
/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
            $this->metrics['steps'][$stepNumber]['name'] = $step->getName();
1✔
288
            $this->metrics['steps'][$stepNumber]['duration'] = Util::convertMicrotime(/** @scrutinizer ignore-type */ $stepStartTime);
1✔
289
            $this->metrics['steps'][$stepNumber]['memory']   = Util::convertMemory(memory_get_usage() - $stepStartMemory);
1✔
290
            $this->getLogger()->info(\sprintf(
1✔
291
                '%s done in %s (%s)',
1✔
292
                $this->metrics['steps'][$stepNumber]['name'],
1✔
293
                $this->metrics['steps'][$stepNumber]['duration'],
1✔
294
                $this->metrics['steps'][$stepNumber]['memory']
1✔
295
            ));
1✔
296
        }
297
        // build duration and memory usage
298
        $this->metrics['total']['duration'] = Util::convertMicrotime(/** @scrutinizer ignore-type */ $startTime);
1✔
299
        $this->metrics['total']['memory']   = Util::convertMemory(memory_get_usage() - $startMemory);
1✔
300
        $this->getLogger()->notice(\sprintf('Built in %s (%s)', $this->metrics['total']['duration'], $this->metrics['total']['memory']));
1✔
301

302
        return $this;
1✔
303
    }
304

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

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

322
        return $this;
1✔
323
    }
324

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

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

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

346
        return $this;
1✔
347
    }
348

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

356
        return $this;
1✔
357
    }
358

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

487
    /**
488
     * Returns list of assets path.
489
     */
490
    public function getAssetsList(): array
491
    {
492
        return $this->assets;
1✔
493
    }
494

495
    /**
496
     * Set menus collection.
497
     */
498
    public function setMenus(array $menus): void
499
    {
500
        $this->menus = $menus;
1✔
501
    }
502

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

511
    /**
512
     * Set taxonomies collection.
513
     */
514
    public function setTaxonomies(array $taxonomies): void
515
    {
516
        $this->taxonomies = $taxonomies;
1✔
517
    }
518

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

527
    /**
528
     * Set renderer object.
529
     */
530
    public function setRenderer(Renderer\Twig $renderer): void
531
    {
532
        $this->renderer = $renderer;
1✔
533
    }
534

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

543
    /**
544
     * Returns metrics array.
545
     */
546
    public function getMetrics(): array
547
    {
UNCOV
548
        return $this->metrics;
×
549
    }
550

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

571
        return self::$version;
1✔
572
    }
573

574
    /**
575
     * Returns current build ID.
576
     */
577
    public static function getBuildId(): string
578
    {
579
        return self::$buildId;
1✔
580
    }
581

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