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

Cecilapp / Cecil / 43731374652

15 Nov 2026 03:42PM UTC coverage: 89.891% (+0.06%) from 89.832%
43731374652

push

github

web-flow
feat(config): load front matter schemas from a schemas/ directory (#2600)

* feat(config): load front matter schemas from a schemas/ directory

One YAML file per key of `pages.schema` (`_all.yml` for `*`), in the
site and in the themes, merged field by field with `pages.schema`.

* test(serve): rebuild the whole site when a schema file changes

* docs: document the schemas directory

* docs(api): regenerate API documentation

* fix(config): merge theme schemas field by field

The `pages.schema` of each theme configuration is kept out of the
merger and merged field by field, and environment variables override
the effective schemas.

* docs(api): regenerate API documentation

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

61 of 63 new or added lines in 2 files covered. (96.83%)

6358 of 7073 relevant lines covered (89.89%)

33.93 hits per line

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

97.32
/src/Config.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\Schema as PageSchema;
17
use Cecil\Config\Deprecations;
18
use Cecil\Config\Merger;
19
use Cecil\Config\SchemaLoader;
20
use Cecil\Exception\ConfigException;
21
use Dflydev\DotAccessData\Data;
22
use Dflydev\DotAccessData\Exception\DataException;
23
use Nette\Schema\Elements\AnyOf;
24
use Nette\Schema\Elements\Structure;
25
use Nette\Schema\Expect;
26
use Nette\Schema\Message;
27
use Nette\Schema\Processor;
28
use Nette\Schema\Schema;
29
use Nette\Schema\ValidationException;
30
use Symfony\Component\Yaml\Exception\ParseException;
31
use Symfony\Component\Yaml\Yaml;
32

33
/**
34
 * Configuration class.
35
 *
36
 * This class is used to manage the configuration of the application.
37
 * It allows to import, export, validate and access configuration data.
38
 * It also provides methods to handle paths, languages, themes, and cache.
39
 */
40
class Config
41
{
42
    public const int IMPORT_PRESERVE = 0;
43
    public const int IMPORT_REPLACE = 1;
44
    public const int IMPORT_MERGE = 2;
45
    public const string LANG_CODE_PATTERN = '([a-z]{2}(-[A-Z]{2})?)'; // "fr" or "fr-FR"
46
    public const string LANG_LOCALE_PATTERN = '[a-z]{2}(_[A-Z]{2})?(_[A-Z]{2})?'; // "fr" or "fr_FR" or "no_NO_NY"
47
    /**
48
     * Configuration keys that are read for the whole site only: their localized value (`languages.<n>.config`) is ignored.
49
     */
50
    public const array NOT_LOCALIZABLE_KEYS = [
51
        'language',
52
        'languages',
53
        'theme',
54
        'cache',
55
        'extensions',
56
        'optimize',
57
        'server',
58
        'data',
59
        'static',
60
        'pages.dir',
61
        'pages.ext',
62
        'pages.frontmatter',
63
        'pages.converter',
64
        'pages.generators',
65
        'pages.default',
66
        'pages.validation',
67
        'pages.schema',
68
        'output.dir',
69
        'output.formats',
70
        'output.postprocessors',
71
        'layouts.dir',
72
        'layouts.extensions',
73
        'layouts.autoescape',
74
        'assets.dir',
75
    ];
76

77
    /**
78
     * Effective configuration: the default configuration, overridden by the themes configuration,
79
     * itself overridden by the site configuration and the environment variables.
80
     * This is a Data object, which allows to use dot notation to access configuration keys.
81
     * For example: $config->get('key.subkey') or $config->has('key.subkey').
82
     * @var Data
83
     */
84
    protected Data $data;
85
    /**
86
     * Default configuration.
87
     */
88
    protected Data $default;
89
    /**
90
     * Themes configuration layer.
91
     * @var array<string, mixed>
92
     */
93
    protected array $themes = [];
94
    /**
95
     * Front matter schemas (`pages.schema`) of the themes configuration, by import order (the first one takes precedence):
96
     * kept out of the themes configuration layer, as they are merged field by field.
97
     * @var array<int|string, array<mixed>>
98
     */
99
    protected array $themesSchemas = [];
100
    /**
101
     * Site configuration layer.
102
     * @var array<string, mixed>
103
     */
104
    protected array $site = [];
105
    /**
106
     * Source directory.
107
     * This is the directory where the source files are located.
108
     * It is used to resolve relative paths in the configuration.
109
     * If not set, it defaults to the current working directory.
110
     * @var string|null
111
     */
112
    protected ?string $sourceDir = null;
113
    /**
114
     * Destination directory.
115
     * This is the directory where the output files will be generated.
116
     * It is used to resolve relative paths in the configuration.
117
     * If not set, it defaults to the source directory.
118
     * @var string|null
119
     */
120
    protected ?string $destinationDir = null;
121
    /**
122
     * Languages list as array.
123
     * This is used to store the languages defined in the configuration.
124
     * It is initialized to null and will be populated when the languages are requested.
125
     * @var array<int, array<string, mixed>>|null
126
     * @see Config::getLanguages()
127
     * @see Config::getLanguageDefault()
128
     */
129
    protected ?array $languages = null;
130

131
    /**
132
     * Build the Config object with the default config + the optional given array.
133
     *
134
     * @param array<string, mixed>|null $config
135
     */
136
    public function __construct(?array $config = null)
137
    {
138
        // default configuration
139
        $defaultConfigFile = Util\File::getRealPath('../config/default.php');
461 ✔
140
        $this->default = new Data(include $defaultConfigFile);
461 ✔
141
        $this->data = new Data($this->default->export());
461 ✔
142
        // import config array if provided
143
        if ($config !== null) {
461 ✔
144
            $this->import($config);
374 ✔
145
        }
146
    }
147

148
    /**
149
     * Imports (and validate) configuration.
150
     * The mode can be:
151
     * - Config::IMPORT_PRESERVE: imports a theme configuration, overridden by the site configuration and by previously imported themes.
152
     * - Config::IMPORT_REPLACE: imports a site configuration, replacing existing lists of items.
153
     * - Config::IMPORT_MERGE: imports a site configuration, concatenating existing lists of items.
154
     *
155
     * The effective configuration is the default configuration, overridden by the themes configuration,
156
     * itself overridden by the site configuration and by the environment variables.
157
     *
158
     * Maps are merged key by key, lists of values are replaced as a whole (combined between themes and site),
159
     * and a map of booleans applied to a list of values adds (`true`) or removes (`false`) items.
160
     * @see Config::mergeValues()
161
     *
162
     * @param array<string, mixed> $config Configuration array to import
163
     * @param self::IMPORT_* $mode Import mode (default: Config::IMPORT_MERGE)
164
     * @param string|null    $source Source of the configuration (ie: file path), used in error messages
165
     *
166
     * @throws ConfigException
167
     */
168
    public function import(array $config, int $mode = self::IMPORT_MERGE, ?string $source = null): void
169
    {
170
        // deprecated options are checked before merging, to report their actual source
171
        Deprecations::check($config, $source);
415 ✔
172
        Deprecations::check($this->getEnvConfig(), 'environment variables', true);
412 ✔
173
        // `theme: <name>` shorthand: imported as a list, so the themes required by a theme can be added to it
174
        if (\is_string($config['theme'] ?? null) && $config['theme'] !== '') {
411 ✔
175
            $config['theme'] = [$config['theme']];
13 ✔
176
        }
177
        if ($mode === self::IMPORT_PRESERVE) {
411 ✔
178
            // front matter schemas are merged field by field (see `setPagesSchema()`), not by the merger
179
            if (\is_array($config['pages'] ?? null) && \array_key_exists('schema', $config['pages'])) {
27 ✔
180
                // indexed by source, so a theme imported again keeps its rank
181
                $this->themesSchemas[$source ?? \count($this->themesSchemas)] = (array) $config['pages']['schema'];
2 ✔
182
                unset($config['pages']['schema']);
2 ✔
183
            }
184
            $this->themes = Merger::merge($config, $this->themes, self::IMPORT_PRESERVE);
27 ✔
185
        } else {
186
            $this->site = Merger::merge($this->site, $config, $mode);
410 ✔
187
        }
188
        $this->load();
411 ✔
189
    }
190

191
    /**
192
     * Loads the effective configuration from its layers (default, themes and site), then validates it.
193
     *
194
     * @throws ConfigException
195
     */
196
    private function load(): void
197
    {
198
        $this->data = new Data(Merger::merge(
411 ✔
199
            $this->default->export(),
411 ✔
200
            Merger::merge($this->themes, $this->site, self::IMPORT_PRESERVE),
411 ✔
201
            self::IMPORT_REPLACE
411 ✔
202
        ));
411 ✔
203
        $this->languages = null;
411 ✔
204
        $this->setFromEnv();     // override configuration with environment variables
411 ✔
205
        $this->setPagesSchema(); // front matter schemas, including the schemas directories
411 ✔
206
        $this->validate();       // validate configuration
411 ✔
207
    }
208

209
    /**
210
     * Sets the effective front matter schemas (`pages.schema`), merged field by field, from the lowest to the highest priority:
211
     * `schemas/` directories of the themes (a theme overrides the themes after it in the list), `pages.schema` of the themes configuration
212
     * (a theme overrides the themes imported after it), `schemas/` directory of the site, `pages.schema` of the site configuration,
213
     * then the environment variables (ie: `CECIL_PAGES_SCHEMA_BLOG_AUTHOR`).
214
     * The `schemas/` directories are loaded once the source directory is set.
215
     *
216
     * @see SchemaLoader
217
     *
218
     * @throws ConfigException
219
     */
220
    private function setPagesSchema(): void
221
    {
222
        $layers = [];
413 ✔
223
        if ($this->sourceDir !== null) {
413 ✔
224
            foreach (array_reverse($this->getTheme() ?? []) as $theme) {
204 ✔
225
                $layers[] = SchemaLoader::load($this->getThemeDirPath($theme, SchemaLoader::DIR), "themes/$theme/" . SchemaLoader::DIR);
21 ✔
226
            }
227
        }
228
        foreach (array_reverse($this->themesSchemas) as $schemas) {
413 ✔
229
            $layers[] = $schemas;
2 ✔
230
        }
231
        if ($this->sourceDir !== null) {
413 ✔
232
            $layers[] = SchemaLoader::load(Util::joinFile($this->sourceDir, SchemaLoader::DIR));
203 ✔
233
        }
234
        $layers[] = (array) ($this->site['pages']['schema'] ?? []);
413 ✔
235
        if (!empty($schemas = SchemaLoader::merge(...$layers))) {
413 ✔
236
            $this->data->set('pages.schema', $schemas);
28 ✔
237
            // environment variables override the front matter schemas too
238
            $this->setFromEnv('pages.schema');
28 ✔
239
        }
240
    }
241

242
    /**
243
     * Get configuration as an array.
244
     *
245
     * @return array<string, mixed>
246
     */
247
    public function export(): array
248
    {
249
        return $this->data->export();
3 ✔
250
    }
251

252
    /**
253
     * Loads and parse a YAML file.
254
     *
255
     * @return array<string, mixed>
256
     */
257
    public static function loadFile(string $file, bool $ignore = false): array
258
    {
259
        if (!Util\File::getFS()->exists($file)) {
20 ✔
260
            if ($ignore) {
18 ✔
261
                return [];
17 ✔
262
            }
263
            throw new ConfigException(\sprintf('File "%s" does not exist.', $file));
1 ✔
264
        }
265
        if (false === $fileContent = Util\File::fileGetContents($file)) {
10 ✔
266
            throw new ConfigException(\sprintf('Unable to read file "%s".', $file));
×
267
        }
268
        try {
269
            return Yaml::parse($fileContent, Yaml::PARSE_DATETIME) ?? [];
10 ✔
270
        } catch (ParseException $e) {
1 ✔
271
            throw new ConfigException(\sprintf('"%s" parsing error: %s', $file, $e->getMessage()));
1 ✔
272
        }
273
    }
274

275
    /**
276
     * Is configuration's key exists?
277
     *
278
     * @param string $key      Configuration key
279
     * @param string $language Language code (optional)
280
     * @param bool   $fallback Set to false to not return the value in the default language as fallback
281
     */
282
    public function has(string $key, ?string $language = null, bool $fallback = true): bool
283
    {
284
        if ($language !== null) {
455 ✔
285
            $langIndex = $this->getLanguageConfigIndex($language);
17 ✔
286
            if ($this->data->has("languages.$langIndex.config.$key")) {
17 ✔
287
                return true;
3 ✔
288
            }
289
            if ($language !== $this->getLanguageDefault() && $fallback === false) {
15 ✔
290
                return $this->default->has($key);
1 ✔
291
            }
292
        }
293

294
        return $this->data->has($key);
455 ✔
295
    }
296

297
    /**
298
     * Get the value of a configuration's key.
299
     *
300
     * @param string $key      Configuration key
301
     * @param string $language Language code (optional)
302
     * @param bool   $fallback Set to false to not return the value in the default language as fallback
303
     *
304
     * @return mixed|null
305
     */
306
    public function get(string $key, ?string $language = null, bool $fallback = true)
307
    {
308
        $value = $this->data->has($key) ? $this->data->get($key) : null;
446 ✔
309
        if ($language !== null) {
446 ✔
310
            if ($language !== $this->getLanguageDefault() && $fallback === false) {
21 ✔
311
                $value = $this->getDefault($key);
5 ✔
312
            }
313
            $langIndex = $this->getLanguageConfigIndex($language);
21 ✔
314
            $keyLang = "languages.$langIndex.config.$key";
21 ✔
315
            if ($this->data->has($keyLang)) {
21 ✔
316
                // localized value overrides the global (or default) value
317
                return $value === null
6 ✔
318
                    ? $this->data->get($keyLang)
2 ✔
319
                    : Merger::mergeValues($value, $this->data->get($keyLang), self::IMPORT_REPLACE, $key);
6 ✔
320
            }
321
        }
322

323
        return $value;
446 ✔
324
    }
325

326
    /**
327
     * Is an option is enabled?
328
     * Checks if the key is set to `false` or if subkey `enabled` is set to `false`.
329
     */
330
    public function isEnabled(string $key, ?string $language = null, bool $fallback = true): bool
331
    {
332
        if ($this->has($key, $language, $fallback) && $this->get($key, $language, $fallback) === true) {
348 ✔
333
            return true;
77 ✔
334
        }
335
        if ($this->has("$key.enabled", $language, $fallback)) {
348 ✔
336
            if ($this->get("$key.enabled", $language, $fallback) === true) {
57 ✔
337
                return true;
33 ✔
338
            }
339
            return false;
34 ✔
340
        }
341
        if ($this->has($key, $language, $fallback) && $this->get($key, $language, $fallback) !== false) {
344 ✔
342
            return true;
23 ✔
343
        }
344

345
        return false;
343 ✔
346
    }
347

348
    /**
349
     * Set the source directory.
350
     *
351
     * The front matter schemas of the `schemas/` directories are loaded from the source directory.
352
     *
353
     * @throws \InvalidArgumentException
354
     * @throws ConfigException
355
     */
356
    public function setSourceDir(string $sourceDir): self
357
    {
358
        if (!is_dir($sourceDir)) {
205 ✔
359
            throw new \InvalidArgumentException(\sprintf('The directory "%s" is not a valid source.', $sourceDir));
1 ✔
360
        }
361
        $this->sourceDir = $sourceDir;
204 ✔
362
        // each schema file is validated when loaded
363
        $this->setPagesSchema();
204 ✔
364

365
        return $this;
198 ✔
366
    }
367

368
    /**
369
     * Get the source directory.
370
     */
371
    public function getSourceDir(): string
372
    {
373
        if ($this->sourceDir === null) {
124 ✔
374
            return getcwd() ?: throw new ConfigException('Unable to get current working directory.');
29 ✔
375
        }
376

377
        return $this->sourceDir;
121 ✔
378
    }
379

380
    /**
381
     * Set the destination directory.
382
     *
383
     * @throws \InvalidArgumentException
384
     */
385
    public function setDestinationDir(string $destinationDir): self
386
    {
387
        if (!is_dir($destinationDir)) {
152 ✔
388
            throw new \InvalidArgumentException(\sprintf('The directory "%s" is not a valid destination.', $destinationDir));
1 ✔
389
        }
390
        $this->destinationDir = $destinationDir;
151 ✔
391

392
        return $this;
151 ✔
393
    }
394

395
    /**
396
     * Get the destination directory.
397
     */
398
    public function getDestinationDir(): string
399
    {
400
        if ($this->destinationDir === null) {
130 ✔
401
            return $this->getSourceDir();
22 ✔
402
        }
403

404
        return $this->destinationDir;
108 ✔
405
    }
406

407
    /*
408
     * Path helpers.
409
     */
410

411
    /**
412
     * Returns the path of the pages directory.
413
     */
414
    public function getPagesPath(): string
415
    {
416
        return Util::joinFile($this->getSourceDir(), (string) $this->get('pages.dir'));
46 ✔
417
    }
418

419
    /**
420
     * Returns the path of the output directory.
421
     */
422
    public function getOutputPath(): string
423
    {
424
        return Util::joinFile($this->getDestinationDir(), (string) $this->get('output.dir'));
25 ✔
425
    }
426

427
    /**
428
     * Returns the path of the data directory.
429
     */
430
    public function getDataPath(): string
431
    {
432
        return Util::joinFile($this->getSourceDir(), (string) $this->get('data.dir'));
31 ✔
433
    }
434

435
    /**
436
     * Returns the path of templates directory.
437
     */
438
    public function getLayoutsPath(): string
439
    {
440
        return Util::joinFile($this->getSourceDir(), (string) $this->get('layouts.dir'));
47 ✔
441
    }
442

443
    /**
444
     * Returns the path of internal templates directory.
445
     */
446
    public function getLayoutsInternalPath(): string
447
    {
448
        return Util\File::getRealPath('../resources/layouts');
32 ✔
449
    }
450

451
    /**
452
     * Returns the templates directories, by priority: site, themes, then internal.
453
     *
454
     * @return list<string>
455
     */
456
    public function getLayoutsPaths(): array
457
    {
458
        $paths = [];
31 ✔
459

460
        // layouts/
461
        if (is_dir($this->getLayoutsPath())) {
31 ✔
462
            $paths[] = $this->getLayoutsPath();
5 ✔
463
        }
464
        // <theme>/layouts/
465
        if ($this->hasTheme()) {
31 ✔
466
            foreach ($this->getTheme() ?? [] as $theme) {
2 ✔
467
                // a theme may not have layouts (e.g.: config/data/assets only)
468
                if (is_dir($this->getThemeDirPath($theme))) {
2 ✔
469
                    $paths[] = $this->getThemeDirPath($theme);
2 ✔
470
                }
471
            }
472
        }
473
        // resources/layouts/
474
        if (is_dir($this->getLayoutsInternalPath())) {
31 ✔
475
            $paths[] = $this->getLayoutsInternalPath();
31 ✔
476
        }
477

478
        return $paths;
31 ✔
479
    }
480

481
    /**
482
     * Returns the layout for a section.
483
     */
484
    public function getLayoutSection(?string $section): ?string
485
    {
486
        if ($layout = $this->get('layouts.sections')[$section] ?? null) {
22 ✔
487
            return $layout;
2 ✔
488
        }
489

490
        return $section;
22 ✔
491
    }
492

493
    /**
494
     * Returns the path of translations directory.
495
     */
496
    public function getTranslationsPath(): string
497
    {
498
        return Util::joinFile($this->getSourceDir(), (string) $this->get('layouts.translations.dir'));
37 ✔
499
    }
500

501
    /**
502
     * Returns the path of internal translations directory.
503
     */
504
    public function getTranslationsInternalPath(): string
505
    {
506
        return Util\File::getRealPath('../resources/translations');
37 ✔
507
    }
508

509
    /**
510
     * Returns the path of themes directory.
511
     */
512
    public function getThemesPath(): string
513
    {
514
        return Util::joinFile($this->getSourceDir(), 'themes');
33 ✔
515
    }
516

517
    /**
518
     * Returns the path of static files directory.
519
     */
520
    public function getStaticPath(): string
521
    {
522
        return Util::joinFile($this->getSourceDir(), (string) $this->get('static.dir'));
45 ✔
523
    }
524

525
    /**
526
     * Returns the path of assets files directory.
527
     */
528
    public function getAssetsPath(): string
529
    {
530
        return Util::joinFile($this->getSourceDir(), (string) $this->get('assets.dir'));
45 ✔
531
    }
532

533
    /**
534
     * Returns the path of remote assets files directory (in cache).
535
     *
536
     * @return string
537
     */
538
    public function getAssetsRemotePath(): string
539
    {
540
        return Util::joinFile($this->getCacheAssetsPath(), 'remote');
1 ✔
541
    }
542

543
    /**
544
     * Returns cache path.
545
     *
546
     * @throws ConfigException
547
     */
548
    public function getCachePath(): string
549
    {
550
        if (empty((string) $this->get('cache.dir'))) {
116 ✔
551
            throw new ConfigException(\sprintf('The cache directory (`%s`) is not defined.', 'cache.dir'));
1 ✔
552
        }
553
        if ($this->isCacheDirIsAbsolute()) {
115 ✔
554
            $cacheDir = Util::joinFile((string) $this->get('cache.dir'), 'cecil');
1 ✔
555
            Util\File::getFS()->mkdir($cacheDir);
1 ✔
556

557
            return $cacheDir;
1 ✔
558
        }
559

560
        return Util::joinFile($this->getDestinationDir(), (string) $this->get('cache.dir'));
114 ✔
561
    }
562

563
    /**
564
     * Returns cache path of templates.
565
     */
566
    public function getCacheTemplatesPath(): string
567
    {
568
        return Util::joinFile($this->getCachePath(), 'templates');
37 ✔
569
    }
570

571
    /**
572
     * Returns cache path of translations.
573
     */
574
    public function getCacheTranslationsPath(): string
575
    {
576
        return Util::joinFile($this->getCachePath(), 'translations');
37 ✔
577
    }
578

579
    /**
580
     * Returns cache path of assets.
581
     */
582
    public function getCacheAssetsPath(): string
583
    {
584
        return Util::joinFile($this->getCachePath(), 'assets');
2 ✔
585
    }
586

587
    /*
588
     * Output helpers.
589
     */
590

591
    /**
592
     * Returns the property value of an output format.
593
     *
594
     * @return string|array<int, string>|null
595
     *
596
     * @throws ConfigException
597
     */
598
    public function getOutputFormatProperty(string $name, string $property): string|array|null
599
    {
600
        $properties = array_column((array) $this->get('output.formats'), $property, 'name');
47 ✔
601
        if (empty($properties)) {
47 ✔
602
            throw new ConfigException(\sprintf('Property "%s" is not defined for format "%s".', $property, $name));
1 ✔
603
        }
604

605
        return $properties[$name] ?? null;
46 ✔
606
    }
607

608
    /*
609
     * Assets helpers.
610
     */
611

612
    /**
613
     * Returns asset image widths.
614
     *
615
     * @return array<int, int>
616
     */
617
    public function getAssetsImagesWidths(): array
618
    {
619
        return $this->get('assets.images.responsive.widths');
3 ✔
620
    }
621

622
    /**
623
     * Returns asset image sizes.
624
     *
625
     * @return array<string, string>
626
     */
627
    public function getAssetsImagesSizes(): array
628
    {
629
        return $this->get('assets.images.responsive.sizes');
2 ✔
630
    }
631

632
    /**
633
     * Returns asset image densities.
634
     *
635
     * @return array<int, int|float>
636
     */
637
    public function getAssetsImagesDensities(): array
638
    {
639
        return $this->get('assets.images.responsive.densities');
2 ✔
640
    }
641

642
    /*
643
     * Theme helpers.
644
     */
645

646
    /**
647
     * Returns theme(s) as an array.
648
     *
649
     * @return array<int, string>|null
650
     */
651
    public function getTheme(): ?array
652
    {
653
        if ($themes = $this->get('theme')) {
322 ✔
654
            if (\is_array($themes)) {
33 ✔
655
                return $themes;
33 ✔
656
            }
657

658
            return [$themes];
×
659
        }
660

661
        return null;
305 ✔
662
    }
663

664
    /**
665
     * Has a (valid) theme(s)?
666
     *
667
     * @throws ConfigException
668
     */
669
    public function hasTheme(): bool
670
    {
671
        if ($themes = $this->getTheme()) {
49 ✔
672
            foreach ($themes as $theme) {
9 ✔
673
                if (!Util\File::getFS()->exists($this->getThemeDirPath($theme, 'layouts')) && !Util\File::getFS()->exists(Util::joinFile($this->getThemesPath(), $theme, 'config.yml'))) {
9 ✔
674
                    $requirer = $this->getThemeRequirer($theme);
3 ✔
675

676
                    throw new ConfigException(\sprintf('Theme "%s"%s not found. Did you forgot to install it?', $theme, $requirer !== null ? \sprintf(' (required by theme "%s")', $requirer) : ''));
3 ✔
677
                }
678
            }
679

680
            return true;
6 ✔
681
        }
682

683
        return false;
41 ✔
684
    }
685

686
    /**
687
     * Returns the name of the theme requiring a theme (in the `theme` option of its configuration),
688
     * or null if the theme is set by the site configuration.
689
     */
690
    private function getThemeRequirer(string $theme): ?string
691
    {
692
        if (\in_array($theme, (array) ($this->site['theme'] ?? []), true)) {
3 ✔
693
            return null;
2 ✔
694
        }
695
        foreach ($this->getTheme() ?? [] as $name) {
1 ✔
696
            try {
697
                $config = self::loadFile(Util::joinFile($this->getThemesPath(), $name, 'config.yml'), true);
1 ✔
698
            } catch (ConfigException) {
×
699
                continue;
×
700
            }
701
            if ($name !== $theme && \in_array($theme, (array) ($config['theme'] ?? []), true)) {
1 ✔
702
                return $name;
1 ✔
703
            }
704
        }
705

706
        return null;
×
707
    }
708

709
    /**
710
     * Returns the path of a specific theme's directory.
711
     * ("layouts" by default).
712
     */
713
    public function getThemeDirPath(string $theme, string $dir = 'layouts'): string
714
    {
715
        return Util::joinFile($this->getThemesPath(), $theme, $dir);
32 ✔
716
    }
717

718
    /*
719
     * Language helpers.
720
     */
721

722
    /**
723
     * Returns an array of available languages.
724
     *
725
     * @return array<int, array<string, mixed>>
726
     *
727
     * @throws ConfigException
728
     */
729
    public function getLanguages(): array
730
    {
731
        if ($this->languages !== null) {
76 ✔
732
            return $this->languages;
45 ✔
733
        }
734
        $languages = array_filter((array) $this->get('languages'), function ($language) {
76 ✔
735
            return !(isset($language['enabled']) && $language['enabled'] === false);
76 ✔
736
        });
76 ✔
737
        if (!\is_int(array_search($this->getLanguageDefault(), array_column($languages, 'code')))) {
76 ✔
738
            throw new ConfigException(\sprintf('The default language "%s" is not listed in "languages".', $this->getLanguageDefault()));
2 ✔
739
        }
740
        $this->languages = $languages;
74 ✔
741

742
        return $this->languages;
74 ✔
743
    }
744

745
    /**
746
     * Returns the default language code (ie: "en", "fr-FR", etc.).
747
     *
748
     * @throws ConfigException
749
     */
750
    public function getLanguageDefault(): string
751
    {
752
        if (!$this->get('language')) {
416 ✔
753
            throw new ConfigException('There is no default "language" key.');
2 ✔
754
        }
755
        if (\is_array($this->get('language'))) {
415 ✔
756
            if (!$this->get('language.code')) {
2 ✔
757
                throw new ConfigException('There is no "language.code" key.');
×
758
            }
759

760
            return $this->get('language.code');
2 ✔
761
        }
762

763
        return $this->get('language');
413 ✔
764
    }
765

766
    /**
767
     * Returns a language code index.
768
     *
769
     * @throws ConfigException
770
     */
771
    public function getLanguageIndex(string $code): int
772
    {
773
        $array = array_column($this->getLanguages(), 'code');
4 ✔
774
        if (false === $index = array_search($code, $array)) {
4 ✔
775
            throw new ConfigException(\sprintf('The language code "%s" is not defined.', $code));
1 ✔
776
        }
777

778
        return $index;
3 ✔
779
    }
780

781
    /**
782
     * Returns the index of a language code in the `languages` configuration (disabled languages included),
783
     * used to read its localized configuration (`languages.<index>.config`).
784
     *
785
     * @throws ConfigException
786
     */
787
    private function getLanguageConfigIndex(string $code): int
788
    {
789
        // enabled languages, indexed by their position in the `languages` configuration
790
        foreach ($this->getLanguages() as $index => $language) {
22 ✔
791
            if (($language['code'] ?? null) === $code) {
22 ✔
792
                return $index;
22 ✔
793
            }
794
        }
795

796
        throw new ConfigException(\sprintf('The language code "%s" is not defined.', $code));
×
797
    }
798

799
    /**
800
     * Returns the localized configuration keys that are ignored (see `NOT_LOCALIZABLE_KEYS`), indexed by language code.
801
     *
802
     * @return array<string, list<string>>
803
     */
804
    public function getIgnoredLocalizedKeys(): array
805
    {
806
        $ignored = [];
16 ✔
807
        foreach ((array) $this->get('languages') as $index => $language) {
16 ✔
808
            if (!\is_array($language) || !isset($language['code']) || !\is_array($language['config'] ?? null)) {
16 ✔
809
                continue;
16 ✔
810
            }
811
            foreach (self::NOT_LOCALIZABLE_KEYS as $key) {
2 ✔
812
                if ($this->hasData("languages.$index.config.$key")) {
2 ✔
813
                    $ignored[(string) $language['code']][] = $key;
1 ✔
814
                }
815
            }
816
        }
817

818
        return $ignored;
16 ✔
819
    }
820

821
    /**
822
     * Returns the property value of a (specified or the default) language.
823
     *
824
     * @throws ConfigException
825
     */
826
    public function getLanguageProperty(string $property, ?string $code = null): string
827
    {
828
        $code = $code ?? $this->getLanguageDefault();
39 ✔
829
        $properties = array_column($this->getLanguages(), $property, 'code');
39 ✔
830
        if (empty($properties)) {
39 ✔
831
            throw new ConfigException(\sprintf('Property "%s" is not defined for language "%s".', $property, $code));
1 ✔
832
        }
833

834
        return $properties[$code];
38 ✔
835
    }
836

837
    /*
838
     * Cache helpers.
839
     */
840

841
    /**
842
     * Is cache dir is absolute to system files
843
     * or relative to project destination?
844
     */
845
    public function isCacheDirIsAbsolute(): bool
846
    {
847
        $path = (string) $this->get('cache.dir');
116 ✔
848
        if (Util\File::getFS()->isAbsolutePath($path)) {
116 ✔
849
            return true;
1 ✔
850
        }
851

852
        return false;
115 ✔
853
    }
854

855
    /*
856
     * Private functions.
857
     */
858

859
    /**
860
     * Returns the default value of a configuration key, if any.
861
     */
862
    private function getDefault(string $key): mixed
863
    {
864
        try {
865
            return $this->default->has($key) ? $this->default->get($key) : null;
5 ✔
866
        } catch (DataException) {
×
867
            return null;
×
868
        }
869
    }
870

871
    /**
872
     * Set configuration from environment variables starting with "CECIL_" (only the given key and its sub-keys, if set).
873
     */
874
    private function setFromEnv(?string $only = null): void
875
    {
876
        foreach ($this->getEnvConfig() as $key => $value) {
411 ✔
877
            if ($only !== null && $key !== $only && !str_starts_with($key, "$only.")) {
10 ✔
NEW
878
                continue;
×
879
            }
880
            $current = $this->data->has($key) ? $this->data->get($key) : null;
10 ✔
881
            $this->data->set($key, Merger::mergeValues($current, $value, self::IMPORT_REPLACE, $key));
10 ✔
882
        }
883
    }
884

885
    /**
886
     * Returns configuration from environment variables starting with "CECIL_", indexed by configuration key
887
     * (ie: `CECIL_PAGES_DIR` -> `pages.dir`).
888
     *
889
     * @return array<string, mixed>
890
     */
891
    private function getEnvConfig(): array
892
    {
893
        $config = [];
412 ✔
894
        foreach (array_merge(getenv() ?: [], $_ENV) as $key => $value) {
412 ✔
895
            if (str_starts_with((string) $key, 'CECIL_')) {
412 ✔
896
                $configKey = str_replace(['cecil_', '_'], ['', '.'], strtolower((string) $key));
11 ✔
897
                $config[$configKey] = $this->castSetValue($value, $configKey);
11 ✔
898
            }
899
        }
900

901
        return $config;
412 ✔
902
    }
903

904
    /**
905
     * Casts a value given as string (ie: by an environment variable), according to the default value of the key:
906
     * - to a number, if the default value is a number;
907
     * - to a boolean, if possible;
908
     * - to a number, if the default value is null (ie: `cache.assets.ttl`).
909
     *
910
     * @param mixed $value
911
     *
912
     * @return bool|int|float|mixed
913
     */
914
    private function castSetValue($value, ?string $key = null)
915
    {
916
        $defaultType = $key !== null ? $this->getDefaultType($key) : null;
11 ✔
917
        $isNumeric = \is_string($value) && is_numeric($value);
11 ✔
918

919
        if ($defaultType === 'number' && $isNumeric) {
11 ✔
920
            return self::toNumber($value);
1 ✔
921
        }
922

923
        $filteredValue = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
11 ✔
924

925
        if ($filteredValue !== null) {
11 ✔
926
            return $filteredValue;
7 ✔
927
        }
928

929
        if ($defaultType === 'null' && $isNumeric) {
8 ✔
930
            return self::toNumber($value);
1 ✔
931
        }
932

933
        return $value;
8 ✔
934
    }
935

936
    /**
937
     * Returns the type of the default value of a configuration key (`number`, `null` or `other`),
938
     * or null if the key doesn't exist in the default configuration.
939
     */
940
    private function getDefaultType(string $key): ?string
941
    {
942
        try {
943
            if (!$this->default->has($key)) {
11 ✔
944
                return null;
11 ✔
945
            }
946
        } catch (DataException) {
×
947
            return null;
×
948
        }
949
        $default = $this->default->get($key);
9 ✔
950

951
        return match (true) {
9 ✔
952
            $default === null                       => 'null',
2 ✔
953
            \is_int($default) || \is_float($default) => 'number',
8 ✔
954
            default                                 => 'other',
9 ✔
955
        };
9 ✔
956
    }
957

958
    /**
959
     * Converts a numeric string to an integer or a float.
960
     */
961
    private static function toNumber(string $value): int|float
962
    {
963
        return preg_match('/^-?\d+$/', $value) ? (int) $value : (float) $value;
1 ✔
964
    }
965

966
    /**
967
     * Validate the configuration.
968
     *
969
     * @throws ConfigException
970
     */
971
    private function validate(): void
972
    {
973
        // structural validation of well-defined sections
974
        $this->validateSchema();
411 ✔
975

976
        // default language must be valid
977
        if (!preg_match('/^' . Config::LANG_CODE_PATTERN . '$/', $this->getLanguageDefault())) {
382 ✔
978
            throw new ConfigException(\sprintf('Default language code "%s" is not valid (e.g.: "language: fr-FR").', $this->getLanguageDefault()));
1 ✔
979
        }
980
    }
981

982
    /**
983
     * Validates well-defined configuration sections against a schema.
984
     * Only targeted sections are processed: the rest of the configuration stays open
985
     * (menus, taxonomies, custom variables, etc.).
986
     *
987
     * @throws ConfigException
988
     */
989
    private function validateSchema(): void
990
    {
991
        $processor = new Processor();
411 ✔
992
        $schemas = $this->getSchemas();
411 ✔
993
        foreach ($schemas as $key => $schema) {
411 ✔
994
            if (!$this->has($key)) {
411 ✔
995
                continue;
382 ✔
996
            }
997
            try {
998
                $processor->process($schema, $this->get($key));
411 ✔
999
            } catch (ValidationException $e) {
29 ✔
1000
                throw new ConfigException(self::schemaErrorMessage($key, $e), previous: $e);
29 ✔
1001
            }
1002
        }
1003
        // localized configuration: the effective value of each language (global value overridden by the localized one) is validated
1004
        foreach ((array) $this->get('languages') as $index => $language) {
383 ✔
1005
            if (!\is_array($language) || !\is_array($language['config'] ?? null)) {
383 ✔
1006
                continue;
380 ✔
1007
            }
1008
            foreach ($schemas as $key => $schema) {
10 ✔
1009
                $keyLang = "languages.$index.config.$key";
10 ✔
1010
                if (!$this->hasData($keyLang)) {
10 ✔
1011
                    continue;
10 ✔
1012
                }
1013
                $value = $this->get($key);
8 ✔
1014
                $localized = $this->data->get($keyLang);
8 ✔
1015
                try {
1016
                    $processor->process($schema, $value === null ? $localized : Merger::mergeValues($value, $localized, self::IMPORT_REPLACE, $key));
8 ✔
1017
                } catch (ValidationException $e) {
1 ✔
1018
                    throw new ConfigException(self::schemaErrorMessage($keyLang, $e), previous: $e);
1 ✔
1019
                }
1020
            }
1021
        }
1022
    }
1023

1024
    /**
1025
     * Is the key exists in the effective configuration (false if a parent key is not an array)?
1026
     */
1027
    private function hasData(string $key): bool
1028
    {
1029
        try {
1030
            return $this->data->has($key);
10 ✔
1031
        } catch (DataException) {
×
1032
            return false;
×
1033
        }
1034
    }
1035

1036
    /**
1037
     * Returns the message of a schema validation error, with the path of each item from the root of the configuration.
1038
     */
1039
    private static function schemaErrorMessage(string $key, ValidationException $e): string
1040
    {
1041
        $messages = [];
30 ✔
1042
        foreach ($e->getMessageObjects() as $message) {
30 ✔
1043
            $message->path = array_merge(explode('.', $key), $message->path);
30 ✔
1044
            if ($message->code === Message::FailedAssertion) {
30 ✔
1045
                $messages[] = \sprintf("Invalid '%s': %s", implode("\u{a0}›\u{a0}", $message->path), $message->variables['assertion'] ?? '');
8 ✔
1046
                continue;
8 ✔
1047
            }
1048
            $messages[] = $message->toString();
22 ✔
1049
        }
1050

1051
        return implode("\n", $messages);
30 ✔
1052
    }
1053

1054
    /**
1055
     * Returns the validation schemas indexed by configuration key.
1056
     *
1057
     * @return array<string, Schema>
1058
     */
1059
    private function getSchemas(): array
1060
    {
1061
        return [
411 ✔
1062
            // main site options
1063
            'title'        => Expect::string(),
411 ✔
1064
            'baseline'     => Expect::string(),
411 ✔
1065
            'baseurl'      => Expect::string(),
411 ✔
1066
            'canonicalurl' => Expect::bool(),
411 ✔
1067
            'description'  => Expect::string(),
411 ✔
1068
            // `theme: <name>` shorthand or a list of theme names
1069
            'theme' => Expect::anyOf(
411 ✔
1070
                Expect::string(),
411 ✔
1071
                Expect::listOf('string')
411 ✔
1072
            ),
411 ✔
1073
            // `cache: true|false` shorthand or a structure with a non-empty `dir` when enabled
1074
            'cache' => Expect::anyOf(
411 ✔
1075
                Expect::bool(),
411 ✔
1076
                self::open([
411 ✔
1077
                    'enabled' => Expect::bool(),
411 ✔
1078
                    'dir'     => Expect::string(),
411 ✔
1079
                    'assets'  => self::open([
411 ✔
1080
                        'ttl'    => Expect::int()->nullable(),
411 ✔
1081
                        'remote' => self::open([
411 ✔
1082
                            'ttl' => Expect::int()->nullable(),
411 ✔
1083
                        ]),
411 ✔
1084
                    ]),
411 ✔
1085
                    'templates'    => self::toggle(),
411 ✔
1086
                    'translations' => self::toggle(),
411 ✔
1087
                ])->assert(
411 ✔
1088
                    fn ($cache) => $cache->enabled === false || trim((string) ($cache->dir ?? '')) !== '',
411 ✔
1089
                    'The cache directory (`cache.dir`) must not be empty when cache is enabled.'
411 ✔
1090
                )
411 ✔
1091
            ),
411 ✔
1092
            // extensions loading options (entries of extensions maps are validated by the extensions loader, according to `extensions.strict`)
1093
            'extensions' => self::open([
411 ✔
1094
                'strict'      => Expect::bool()->nullable(),
411 ✔
1095
                'autoload'    => Expect::arrayOf(Expect::string(), Expect::string()),
411 ✔
1096
                'subscribers' => Expect::array(),
411 ✔
1097
                'plugins'     => Expect::array(),
411 ✔
1098
            ]),
411 ✔
1099
            // output directory and post processors
1100
            'output.dir'            => Expect::string(),
411 ✔
1101
            'output.postprocessors' => Expect::array(),
411 ✔
1102
            // each output format must define a unique `name` and a `mediatype`
1103
            'output.formats' => Expect::arrayOf(
411 ✔
1104
                self::open([
411 ✔
1105
                    'name'      => Expect::string()->required()->assert(fn ($value) => trim((string) $value) !== '', 'Output format "name" must not be empty.'),
411 ✔
1106
                    'mediatype' => Expect::string()->required()->assert(fn ($value) => trim((string) $value) !== '', 'Output format "mediatype" must not be empty.'),
411 ✔
1107
                    'rel'       => Expect::string(),
411 ✔
1108
                    'subpath'   => Expect::string(),
411 ✔
1109
                    'filename'  => Expect::string(),
411 ✔
1110
                    'extension' => Expect::string(),
411 ✔
1111
                    'exclude'   => Expect::listOf('string'),
411 ✔
1112
                ])
411 ✔
1113
            )->assert(
411 ✔
1114
                fn (array $formats) => self::hasUniqueValues($formats, 'name'),
411 ✔
1115
                'Output formats names must be unique.'
411 ✔
1116
            ),
411 ✔
1117
            // formats applied by page type (each type accepts a list of format names)
1118
            'output.pagetypeformats' => self::open([
411 ✔
1119
                'page'       => Expect::listOf('string'),
411 ✔
1120
                'homepage'   => Expect::listOf('string'),
411 ✔
1121
                'section'    => Expect::listOf('string'),
411 ✔
1122
                'vocabulary' => Expect::listOf('string'),
411 ✔
1123
                'term'       => Expect::listOf('string'),
411 ✔
1124
            ]),
411 ✔
1125
            // main language: `language: <code>` shorthand or a structure (a missing or invalid code is reported by `validate()`)
1126
            'language' => Expect::anyOf(
411 ✔
1127
                Expect::scalar(),
411 ✔
1128
                self::open([
411 ✔
1129
                    'code'   => Expect::string(),
411 ✔
1130
                    'prefix' => Expect::bool(),
411 ✔
1131
                ])
411 ✔
1132
            ),
411 ✔
1133
            // each language must define a valid `code` and a valid `locale` (duplicate codes are reported by the site doctor)
1134
            'languages' => Expect::listOf(
411 ✔
1135
                self::open([
411 ✔
1136
                    'code'    => Expect::string()->required()->pattern(Config::LANG_CODE_PATTERN),
411 ✔
1137
                    'name'    => Expect::string(),
411 ✔
1138
                    'locale'  => Expect::string()->required()->pattern(Config::LANG_LOCALE_PATTERN),
411 ✔
1139
                    'enabled' => Expect::bool(),
411 ✔
1140
                ])
411 ✔
1141
            ),
411 ✔
1142
            // date formatting options
1143
            'date' => self::open([
411 ✔
1144
                'format'   => Expect::string(),
411 ✔
1145
                'timezone' => Expect::string(),
411 ✔
1146
            ]),
411 ✔
1147
            // pages management options
1148
            'pages' => self::open([
411 ✔
1149
                'dir'    => Expect::string(),
411 ✔
1150
                'ext'    => Expect::listOf('string'),
411 ✔
1151
                'prefix' => self::open([
411 ✔
1152
                    'separator' => Expect::listOf('string'),
411 ✔
1153
                ]),
411 ✔
1154
                'exclude' => Expect::listOf('string'),
411 ✔
1155
                // `sortby: <variable>` shorthand or a structure
1156
                'sortby' => Expect::anyOf(
411 ✔
1157
                    Expect::string(),
411 ✔
1158
                    self::open([
411 ✔
1159
                        'variable'   => Expect::string(),
411 ✔
1160
                        'desc_title' => Expect::bool(),
411 ✔
1161
                        'reverse'    => Expect::bool(),
411 ✔
1162
                    ])
411 ✔
1163
                ),
411 ✔
1164
                'pagination' => self::toggle([
411 ✔
1165
                    'max'  => Expect::int()->min(1),
411 ✔
1166
                    'path' => Expect::string(),
411 ✔
1167
                ]),
411 ✔
1168
                'frontmatter' => Expect::anyOf('yaml', 'ini', 'toml', 'json'),
411 ✔
1169
                'converter'   => Expect::string(),
411 ✔
1170
                'body'        => self::open([
411 ✔
1171
                    'parser'    => Expect::string(),
411 ✔
1172
                    'toc'       => Expect::listOf('string'),
411 ✔
1173
                    'anchors'   => Expect::anyOf(Expect::bool(), Expect::listOf('string')),
411 ✔
1174
                    'highlight' => self::toggle([
411 ✔
1175
                        'engine' => Expect::string(),
411 ✔
1176
                    ]),
411 ✔
1177
                    'images' => self::open([
411 ✔
1178
                        'formats'            => Expect::listOf('string'),
411 ✔
1179
                        // a width in pixels (`0` to disable), a boolean is still accepted (legacy usage, ignored)
1180
                        'resize'             => Expect::anyOf(Expect::int()->min(0), Expect::bool()),
411 ✔
1181
                        'responsive'         => Expect::anyOf(Expect::bool(), 'width', 'density'),
411 ✔
1182
                        'lazy'               => Expect::bool(),
411 ✔
1183
                        'decoding'           => Expect::bool(),
411 ✔
1184
                        'caption'            => Expect::bool(),
411 ✔
1185
                        'placeholder'        => Expect::string(),
411 ✔
1186
                        'class'              => Expect::string(),
411 ✔
1187
                        'dark_suffix'        => Expect::string()->nullable(),
411 ✔
1188
                        'mobile_suffix'      => Expect::string()->nullable(),
411 ✔
1189
                        'mobile_media_query' => Expect::string(),
411 ✔
1190
                        'remote'             => self::toggle([
411 ✔
1191
                            'fallback' => Expect::string(),
411 ✔
1192
                        ]),
411 ✔
1193
                    ]),
411 ✔
1194
                    'links' => self::open([
411 ✔
1195
                        'embed' => self::toggle([
411 ✔
1196
                            'video' => Expect::listOf('string'),
411 ✔
1197
                            'audio' => Expect::listOf('string'),
411 ✔
1198
                        ]),
411 ✔
1199
                        'external' => self::open([
411 ✔
1200
                            'blank'      => Expect::bool(),
411 ✔
1201
                            'noopener'   => Expect::bool(),
411 ✔
1202
                            'noreferrer' => Expect::bool(),
411 ✔
1203
                            'nofollow'   => Expect::bool(),
411 ✔
1204
                        ]),
411 ✔
1205
                    ]),
411 ✔
1206
                    'excerpt' => self::open([
411 ✔
1207
                        'separator' => Expect::string(),
411 ✔
1208
                        'capture'   => Expect::anyOf('before', 'after'),
411 ✔
1209
                    ]),
411 ✔
1210
                ]),
411 ✔
1211
                'generators' => Expect::array(),
411 ✔
1212
                // front matter validation mode
1213
                'validation' => Expect::anyOf(false, 'warning', 'error', 'strict'),
411 ✔
1214
                // front matter schemas, indexed by section or by page (`*` for all pages): each field is defined by its type or by a map of rules (recursive with `fields` and `items`)
1215
                'schema' => Expect::arrayOf(
411 ✔
1216
                    Expect::arrayOf(PageSchema::definition(), Expect::string()),
411 ✔
1217
                    Expect::string()
411 ✔
1218
                )->nullable(),
411 ✔
1219
            ]),
411 ✔
1220
            // default pages, indexed by ID: each published page must define a `path` (other keys are front matter variables)
1221
            'pages.default' => Expect::arrayOf(
411 ✔
1222
                Expect::structure([
411 ✔
1223
                    'path'         => Expect::anyOf(Expect::string(), Expect::int()),
411 ✔
1224
                    'published'    => Expect::bool(),
411 ✔
1225
                    'excluded'     => Expect::bool(),
411 ✔
1226
                    'exclude'      => Expect::bool(),
411 ✔
1227
                    'multilingual' => Expect::bool(),
411 ✔
1228
                    'uglyurl'      => Expect::bool(),
411 ✔
1229
                    'output'       => Expect::anyOf(Expect::string(), Expect::listOf('string')),
411 ✔
1230
                ])->otherItems(Expect::mixed())->assert(
411 ✔
1231
                    fn ($page) => $page->published === false || $page->path !== null,
411 ✔
1232
                    'A published default page must define a `path`.'
411 ✔
1233
                ),
411 ✔
1234
                Expect::anyOf(Expect::string(), Expect::int())
411 ✔
1235
            ),
411 ✔
1236
            // data files options
1237
            'data' => self::open([
411 ✔
1238
                'dir'  => Expect::string(),
411 ✔
1239
                'ext'  => Expect::listOf('string'),
411 ✔
1240
                'load' => Expect::bool(),
411 ✔
1241
            ]),
411 ✔
1242
            // assets options
1243
            'assets' => self::open([
411 ✔
1244
                'dir'         => Expect::string(),
411 ✔
1245
                'target'      => Expect::string(),
411 ✔
1246
                'fingerprint' => Expect::bool(),
411 ✔
1247
                'compile'     => self::open([
411 ✔
1248
                    'style' => Expect::string()->assert(
411 ✔
1249
                        fn ($value) => \in_array(strtolower((string) $value), ['expanded', 'compressed'], true),
411 ✔
1250
                        'The compilation style must be "expanded" or "compressed".'
411 ✔
1251
                    ),
411 ✔
1252
                    'import'    => Expect::listOf('string'),
411 ✔
1253
                    'sourcemap' => Expect::bool(),
411 ✔
1254
                    'variables' => Expect::array(),
411 ✔
1255
                ]),
411 ✔
1256
                'minify' => Expect::bool(),
411 ✔
1257
                'remote' => self::open([
411 ✔
1258
                    'useragent' => Expect::arrayOf(Expect::string(), Expect::string()),
411 ✔
1259
                    'timeout'   => Expect::int()->min(0),
411 ✔
1260
                ]),
411 ✔
1261
                'images' => self::open([
411 ✔
1262
                    'optimize'   => self::toggle(),
411 ✔
1263
                    'quality'    => Expect::int()->min(0)->max(100),
411 ✔
1264
                    'responsive' => self::open([
411 ✔
1265
                        'widths'    => Expect::listOf(Expect::int()->min(1)),
411 ✔
1266
                        'sizes'     => Expect::arrayOf(Expect::string(), Expect::string()),
411 ✔
1267
                        'densities' => Expect::listOf(Expect::type('int|float')->min(1)),
411 ✔
1268
                    ]),
411 ✔
1269
                    'cdn' => self::toggle([
411 ✔
1270
                        'url'       => Expect::string(),
411 ✔
1271
                        'svg'       => Expect::bool(),
411 ✔
1272
                        'remote'    => Expect::bool(),
411 ✔
1273
                        'account'   => Expect::string(),
411 ✔
1274
                        'canonical' => Expect::bool(),
411 ✔
1275
                    ]),
411 ✔
1276
                ]),
411 ✔
1277
            ]),
411 ✔
1278
            // static files options
1279
            'static' => self::open([
411 ✔
1280
                'dir'     => Expect::string(),
411 ✔
1281
                'target'  => Expect::string(),
411 ✔
1282
                'exclude' => Expect::listOf('string'),
411 ✔
1283
                'load'    => Expect::bool(),
411 ✔
1284
            ]),
411 ✔
1285
            // layouts and templates options
1286
            'layouts' => self::open([
411 ✔
1287
                'dir' => Expect::string(),
411 ✔
1288
                // `null` to use the template extension based strategy
1289
                'autoescape' => Expect::anyOf(Expect::bool(), Expect::string())->nullable(),
411 ✔
1290
                'images'     => self::open([
411 ✔
1291
                    'formats'            => Expect::listOf('string'),
411 ✔
1292
                    'responsive'         => Expect::anyOf(Expect::bool(), 'width', 'density'),
411 ✔
1293
                    'placeholder'        => Expect::string(),
411 ✔
1294
                    'dark_suffix'        => Expect::string()->nullable(),
411 ✔
1295
                    'mobile_suffix'      => Expect::string()->nullable(),
411 ✔
1296
                    'mobile_media_query' => Expect::string(),
411 ✔
1297
                ]),
411 ✔
1298
                'highlight' => self::open([
411 ✔
1299
                    'engine' => Expect::string(),
411 ✔
1300
                ]),
411 ✔
1301
                'translations' => self::open([
411 ✔
1302
                    'dir'     => Expect::string(),
411 ✔
1303
                    'formats' => Expect::arrayOf(
411 ✔
1304
                        self::open([
411 ✔
1305
                            'loader' => Expect::string(),
411 ✔
1306
                            'ext'    => Expect::listOf('string'),
411 ✔
1307
                        ]),
411 ✔
1308
                        Expect::string()
411 ✔
1309
                    ),
411 ✔
1310
                ]),
411 ✔
1311
                'extensions' => Expect::array(),
411 ✔
1312
                'components' => self::open([
411 ✔
1313
                    'dir' => Expect::string(),
411 ✔
1314
                    'ext' => Expect::string(),
411 ✔
1315
                ]),
411 ✔
1316
                'sections' => Expect::arrayOf(Expect::string(), Expect::string()),
411 ✔
1317
            ]),
411 ✔
1318
            // `optimize: true|false` shorthand or a structure enabling optimization by file type
1319
            'optimize' => self::toggle([
411 ✔
1320
                'html'   => self::toggle(['ext' => Expect::listOf('string')]),
411 ✔
1321
                'css'    => self::toggle(['ext' => Expect::listOf('string')]),
411 ✔
1322
                'js'     => self::toggle(['ext' => Expect::listOf('string')]),
411 ✔
1323
                'images' => self::toggle(['ext' => Expect::listOf('string')]),
411 ✔
1324
            ]),
411 ✔
1325
            // local preview server custom HTTP headers
1326
            'server.headers' => Expect::listOf(
411 ✔
1327
                self::open([
411 ✔
1328
                    'path'    => Expect::string()->required(),
411 ✔
1329
                    'headers' => Expect::listOf(
411 ✔
1330
                        self::open([
411 ✔
1331
                            'key'   => Expect::string()->required(),
411 ✔
1332
                            'value' => Expect::scalar()->required(),
411 ✔
1333
                        ])
411 ✔
1334
                    )->required(),
411 ✔
1335
                ])
411 ✔
1336
            ),
411 ✔
1337
        ];
411 ✔
1338
    }
1339

1340
    /**
1341
     * Returns an open structure schema: declared items are validated, other items are allowed.
1342
     *
1343
     * @param array<string, Schema> $items
1344
     */
1345
    private static function open(array $items): Structure
1346
    {
1347
        return Expect::structure($items)->otherItems(Expect::mixed());
411 ✔
1348
    }
1349

1350
    /**
1351
     * Returns the schema of an option that can be enabled or disabled:
1352
     * `<option>: true|false` shorthand, or an open structure with an `enabled` key and the given items.
1353
     *
1354
     * @param array<string, Schema> $items
1355
     */
1356
    private static function toggle(array $items = []): AnyOf
1357
    {
1358
        return Expect::anyOf(
411 ✔
1359
            Expect::bool(),
411 ✔
1360
            self::open(['enabled' => Expect::bool()] + $items)
411 ✔
1361
        );
411 ✔
1362
    }
1363

1364
    /**
1365
     * Checks that the items of a list (validated as structures) have unique values for the given key.
1366
     *
1367
     * @param array<int|string, object> $items
1368
     */
1369
    private static function hasUniqueValues(array $items, string $key): bool
1370
    {
1371
        $values = array_filter(array_column($items, $key), fn ($value) => $value !== null);
405 ✔
1372

1373
        return \count($values) === \count(array_unique($values));
405 ✔
1374
    }
1375
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc