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

Cecilapp / Cecil / 41927136286

04 Nov 2026 10:39PM UTC coverage: 89.464% (+0.2%) from 89.297%
41927136286

push

github

web-flow
feat(config): extend schema validation of configuration (#2582)

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

247 of 257 new or added lines in 2 files covered. (96.11%)

5995 of 6701 relevant lines covered (89.46%)

29.52 hits per line

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

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

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

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

121
    /**
122
     * Build the Config object with the default config + the optional given array.
123
     *
124
     * @param array<string, mixed>|null $config
125
     */
126
    public function __construct(?array $config = null)
127
    {
128
        // default configuration
129
        $defaultConfigFile = Util\File::getRealPath('../config/default.php');
412 ✔
130
        $this->default = new Data(include $defaultConfigFile);
412 ✔
131
        $this->data = new Data($this->default->export());
412 ✔
132
        // import config array if provided
133
        if ($config !== null) {
412 ✔
134
            $this->import($config);
325 ✔
135
        }
136
    }
137

138
    /**
139
     * Imports (and validate) configuration.
140
     * The mode can be:
141
     * - Config::IMPORT_PRESERVE: imports a theme configuration, overridden by the site configuration and by previously imported themes.
142
     * - Config::IMPORT_REPLACE: imports a site configuration, replacing existing lists of items.
143
     * - Config::IMPORT_MERGE: imports a site configuration, concatenating existing lists of items.
144
     *
145
     * The effective configuration is the default configuration, overridden by the themes configuration,
146
     * itself overridden by the site configuration and by the environment variables.
147
     *
148
     * Maps are merged key by key, lists of values are replaced as a whole (combined between themes and site),
149
     * and a map of booleans applied to a list of values adds (`true`) or removes (`false`) items.
150
     * @see Config::mergeValues()
151
     *
152
     * @param array<string, mixed> $config Configuration array to import
153
     * @param self::IMPORT_* $mode Import mode (default: Config::IMPORT_MERGE)
154
     * @param string|null    $source Source of the configuration (ie: file path), used in error messages
155
     *
156
     * @throws ConfigException
157
     */
158
    public function import(array $config, int $mode = self::IMPORT_MERGE, ?string $source = null): void
159
    {
160
        // deprecated options are checked before merging, to report their actual source
161
        Deprecations::check($config, $source);
366 ✔
162
        Deprecations::check($this->getEnvConfig(), 'environment variables', true);
363 ✔
163
        if ($mode === self::IMPORT_PRESERVE) {
362 ✔
164
            $this->themes = Merger::merge($config, $this->themes, self::IMPORT_PRESERVE);
18 ✔
165
        } else {
166
            $this->site = Merger::merge($this->site, $config, $mode);
361 ✔
167
        }
168
        $this->data = new Data(Merger::merge(
362 ✔
169
            $this->default->export(),
362 ✔
170
            Merger::merge($this->themes, $this->site, self::IMPORT_PRESERVE),
362 ✔
171
            self::IMPORT_REPLACE
362 ✔
172
        ));
362 ✔
173
        $this->languages = null;
362 ✔
174
        $this->setFromEnv(); // override configuration with environment variables
362 ✔
175
        $this->validate();   // validate configuration
362 ✔
176
    }
177

178
    /**
179
     * Get configuration as an array.
180
     *
181
     * @return array<string, mixed>
182
     */
183
    public function export(): array
184
    {
185
        return $this->data->export();
3 ✔
186
    }
187

188
    /**
189
     * Loads and parse a YAML file.
190
     *
191
     * @return array<string, mixed>
192
     */
193
    public static function loadFile(string $file, bool $ignore = false): array
194
    {
195
        if (!Util\File::getFS()->exists($file)) {
11 ✔
196
            if ($ignore) {
10 ✔
197
                return [];
9 ✔
198
            }
199
            throw new ConfigException(\sprintf('File "%s" does not exist.', $file));
1 ✔
200
        }
201
        if (false === $fileContent = Util\File::fileGetContents($file)) {
3 ✔
202
            throw new ConfigException(\sprintf('Unable to read file "%s".', $file));
×
203
        }
204
        try {
205
            return Yaml::parse($fileContent, Yaml::PARSE_DATETIME) ?? [];
3 ✔
206
        } catch (ParseException $e) {
1 ✔
207
            throw new ConfigException(\sprintf('"%s" parsing error: %s', $file, $e->getMessage()));
1 ✔
208
        }
209
    }
210

211
    /**
212
     * Is configuration's key exists?
213
     *
214
     * @param string $key      Configuration key
215
     * @param string $language Language code (optional)
216
     * @param bool   $fallback Set to false to not return the value in the default language as fallback
217
     */
218
    public function has(string $key, ?string $language = null, bool $fallback = true): bool
219
    {
220
        if ($language !== null) {
406 ✔
221
            $langIndex = $this->getLanguageConfigIndex($language);
15 ✔
222
            if ($this->data->has("languages.$langIndex.config.$key")) {
15 ✔
223
                return true;
3 ✔
224
            }
225
            if ($language !== $this->getLanguageDefault() && $fallback === false) {
13 ✔
226
                return $this->default->has($key);
1 ✔
227
            }
228
        }
229

230
        return $this->data->has($key);
406 ✔
231
    }
232

233
    /**
234
     * Get the value of a configuration's key.
235
     *
236
     * @param string $key      Configuration key
237
     * @param string $language Language code (optional)
238
     * @param bool   $fallback Set to false to not return the value in the default language as fallback
239
     *
240
     * @return mixed|null
241
     */
242
    public function get(string $key, ?string $language = null, bool $fallback = true)
243
    {
244
        $value = $this->data->has($key) ? $this->data->get($key) : null;
397 ✔
245
        if ($language !== null) {
397 ✔
246
            if ($language !== $this->getLanguageDefault() && $fallback === false) {
19 ✔
247
                $value = $this->getDefault($key);
3 ✔
248
            }
249
            $langIndex = $this->getLanguageConfigIndex($language);
19 ✔
250
            $keyLang = "languages.$langIndex.config.$key";
19 ✔
251
            if ($this->data->has($keyLang)) {
19 ✔
252
                // localized value overrides the global (or default) value
253
                return $value === null
6 ✔
254
                    ? $this->data->get($keyLang)
2 ✔
255
                    : Merger::mergeValues($value, $this->data->get($keyLang), self::IMPORT_REPLACE, $key);
6 ✔
256
            }
257
        }
258

259
        return $value;
397 ✔
260
    }
261

262
    /**
263
     * Is an option is enabled?
264
     * Checks if the key is set to `false` or if subkey `enabled` is set to `false`.
265
     */
266
    public function isEnabled(string $key, ?string $language = null, bool $fallback = true): bool
267
    {
268
        if ($this->has($key, $language, $fallback) && $this->get($key, $language, $fallback) === true) {
323 ✔
269
            return true;
73 ✔
270
        }
271
        if ($this->has("$key.enabled", $language, $fallback)) {
323 ✔
272
            if ($this->get("$key.enabled", $language, $fallback) === true) {
55 ✔
273
                return true;
31 ✔
274
            }
275
            return false;
32 ✔
276
        }
277
        if ($this->has($key, $language, $fallback) && $this->get($key, $language, $fallback) !== false) {
319 ✔
278
            return true;
18 ✔
279
        }
280

281
        return false;
318 ✔
282
    }
283

284
    /**
285
     * Set the source directory.
286
     *
287
     * @throws \InvalidArgumentException
288
     */
289
    public function setSourceDir(string $sourceDir): self
290
    {
291
        if (!is_dir($sourceDir)) {
172 ✔
292
            throw new \InvalidArgumentException(\sprintf('The directory "%s" is not a valid source.', $sourceDir));
1 ✔
293
        }
294
        $this->sourceDir = $sourceDir;
171 ✔
295

296
        return $this;
171 ✔
297
    }
298

299
    /**
300
     * Get the source directory.
301
     */
302
    public function getSourceDir(): string
303
    {
304
        if ($this->sourceDir === null) {
102 ✔
305
            return getcwd() ?: throw new ConfigException('Unable to get current working directory.');
21 ✔
306
        }
307

308
        return $this->sourceDir;
99 ✔
309
    }
310

311
    /**
312
     * Set the destination directory.
313
     *
314
     * @throws \InvalidArgumentException
315
     */
316
    public function setDestinationDir(string $destinationDir): self
317
    {
318
        if (!is_dir($destinationDir)) {
140 ✔
319
            throw new \InvalidArgumentException(\sprintf('The directory "%s" is not a valid destination.', $destinationDir));
1 ✔
320
        }
321
        $this->destinationDir = $destinationDir;
139 ✔
322

323
        return $this;
139 ✔
324
    }
325

326
    /**
327
     * Get the destination directory.
328
     */
329
    public function getDestinationDir(): string
330
    {
331
        if ($this->destinationDir === null) {
126 ✔
332
            return $this->getSourceDir();
22 ✔
333
        }
334

335
        return $this->destinationDir;
104 ✔
336
    }
337

338
    /*
339
     * Path helpers.
340
     */
341

342
    /**
343
     * Returns the path of the pages directory.
344
     */
345
    public function getPagesPath(): string
346
    {
347
        return Util::joinFile($this->getSourceDir(), (string) $this->get('pages.dir'));
34 ✔
348
    }
349

350
    /**
351
     * Returns the path of the output directory.
352
     */
353
    public function getOutputPath(): string
354
    {
355
        return Util::joinFile($this->getDestinationDir(), (string) $this->get('output.dir'));
23 ✔
356
    }
357

358
    /**
359
     * Returns the path of the data directory.
360
     */
361
    public function getDataPath(): string
362
    {
363
        return Util::joinFile($this->getSourceDir(), (string) $this->get('data.dir'));
29 ✔
364
    }
365

366
    /**
367
     * Returns the path of templates directory.
368
     */
369
    public function getLayoutsPath(): string
370
    {
371
        return Util::joinFile($this->getSourceDir(), (string) $this->get('layouts.dir'));
45 ✔
372
    }
373

374
    /**
375
     * Returns the path of internal templates directory.
376
     */
377
    public function getLayoutsInternalPath(): string
378
    {
379
        return Util\File::getRealPath('../resources/layouts');
30 ✔
380
    }
381

382
    /**
383
     * Returns the templates directories, by priority: site, themes, then internal.
384
     *
385
     * @return list<string>
386
     */
387
    public function getLayoutsPaths(): array
388
    {
389
        $paths = [];
29 ✔
390

391
        // layouts/
392
        if (is_dir($this->getLayoutsPath())) {
29 ✔
393
            $paths[] = $this->getLayoutsPath();
3 ✔
394
        }
395
        // <theme>/layouts/
396
        if ($this->hasTheme()) {
29 ✔
397
            foreach ($this->getTheme() ?? [] as $theme) {
2 ✔
398
                // a theme may not have layouts (e.g.: config/data/assets only)
399
                if (is_dir($this->getThemeDirPath($theme))) {
2 ✔
400
                    $paths[] = $this->getThemeDirPath($theme);
2 ✔
401
                }
402
            }
403
        }
404
        // resources/layouts/
405
        if (is_dir($this->getLayoutsInternalPath())) {
29 ✔
406
            $paths[] = $this->getLayoutsInternalPath();
29 ✔
407
        }
408

409
        return $paths;
29 ✔
410
    }
411

412
    /**
413
     * Returns the layout for a section.
414
     */
415
    public function getLayoutSection(?string $section): ?string
416
    {
417
        if ($layout = $this->get('layouts.sections')[$section] ?? null) {
20 ✔
418
            return $layout;
2 ✔
419
        }
420

421
        return $section;
20 ✔
422
    }
423

424
    /**
425
     * Returns the path of translations directory.
426
     */
427
    public function getTranslationsPath(): string
428
    {
429
        return Util::joinFile($this->getSourceDir(), (string) $this->get('layouts.translations.dir'));
35 ✔
430
    }
431

432
    /**
433
     * Returns the path of internal translations directory.
434
     */
435
    public function getTranslationsInternalPath(): string
436
    {
437
        return Util\File::getRealPath('../resources/translations');
35 ✔
438
    }
439

440
    /**
441
     * Returns the path of themes directory.
442
     */
443
    public function getThemesPath(): string
444
    {
445
        return Util::joinFile($this->getSourceDir(), 'themes');
23 ✔
446
    }
447

448
    /**
449
     * Returns the path of static files directory.
450
     */
451
    public function getStaticPath(): string
452
    {
453
        return Util::joinFile($this->getSourceDir(), (string) $this->get('static.dir'));
43 ✔
454
    }
455

456
    /**
457
     * Returns the path of assets files directory.
458
     */
459
    public function getAssetsPath(): string
460
    {
461
        return Util::joinFile($this->getSourceDir(), (string) $this->get('assets.dir'));
41 ✔
462
    }
463

464
    /**
465
     * Returns the path of remote assets files directory (in cache).
466
     *
467
     * @return string
468
     */
469
    public function getAssetsRemotePath(): string
470
    {
471
        return Util::joinFile($this->getCacheAssetsPath(), 'remote');
1 ✔
472
    }
473

474
    /**
475
     * Returns cache path.
476
     *
477
     * @throws ConfigException
478
     */
479
    public function getCachePath(): string
480
    {
481
        if (empty((string) $this->get('cache.dir'))) {
112 ✔
482
            throw new ConfigException(\sprintf('The cache directory (`%s`) is not defined.', 'cache.dir'));
1 ✔
483
        }
484
        if ($this->isCacheDirIsAbsolute()) {
111 ✔
485
            $cacheDir = Util::joinFile((string) $this->get('cache.dir'), 'cecil');
1 ✔
486
            Util\File::getFS()->mkdir($cacheDir);
1 ✔
487

488
            return $cacheDir;
1 ✔
489
        }
490

491
        return Util::joinFile($this->getDestinationDir(), (string) $this->get('cache.dir'));
110 ✔
492
    }
493

494
    /**
495
     * Returns cache path of templates.
496
     */
497
    public function getCacheTemplatesPath(): string
498
    {
499
        return Util::joinFile($this->getCachePath(), 'templates');
35 ✔
500
    }
501

502
    /**
503
     * Returns cache path of translations.
504
     */
505
    public function getCacheTranslationsPath(): string
506
    {
507
        return Util::joinFile($this->getCachePath(), 'translations');
35 ✔
508
    }
509

510
    /**
511
     * Returns cache path of assets.
512
     */
513
    public function getCacheAssetsPath(): string
514
    {
515
        return Util::joinFile($this->getCachePath(), 'assets');
2 ✔
516
    }
517

518
    /*
519
     * Output helpers.
520
     */
521

522
    /**
523
     * Returns the property value of an output format.
524
     *
525
     * @return string|array<int, string>|null
526
     *
527
     * @throws ConfigException
528
     */
529
    public function getOutputFormatProperty(string $name, string $property): string|array|null
530
    {
531
        $properties = array_column((array) $this->get('output.formats'), $property, 'name');
41 ✔
532
        if (empty($properties)) {
41 ✔
533
            throw new ConfigException(\sprintf('Property "%s" is not defined for format "%s".', $property, $name));
1 ✔
534
        }
535

536
        return $properties[$name] ?? null;
40 ✔
537
    }
538

539
    /*
540
     * Assets helpers.
541
     */
542

543
    /**
544
     * Returns asset image widths.
545
     *
546
     * @return array<int, int>
547
     */
548
    public function getAssetsImagesWidths(): array
549
    {
550
        return $this->get('assets.images.responsive.widths');
3 ✔
551
    }
552

553
    /**
554
     * Returns asset image sizes.
555
     *
556
     * @return array<string, string>
557
     */
558
    public function getAssetsImagesSizes(): array
559
    {
560
        return $this->get('assets.images.responsive.sizes');
2 ✔
561
    }
562

563
    /**
564
     * Returns asset image densities.
565
     *
566
     * @return array<int, int|float>
567
     */
568
    public function getAssetsImagesDensities(): array
569
    {
570
        return $this->get('assets.images.responsive.densities');
2 ✔
571
    }
572

573
    /*
574
     * Theme helpers.
575
     */
576

577
    /**
578
     * Returns theme(s) as an array.
579
     *
580
     * @return array<int, string>|null
581
     */
582
    public function getTheme(): ?array
583
    {
584
        if ($themes = $this->get('theme')) {
86 ✔
585
            if (\is_array($themes)) {
23 ✔
586
                return $themes;
17 ✔
587
            }
588

589
            return [$themes];
20 ✔
590
        }
591

592
        return null;
77 ✔
593
    }
594

595
    /**
596
     * Has a (valid) theme(s)?
597
     *
598
     * @throws ConfigException
599
     */
600
    public function hasTheme(): bool
601
    {
602
        if ($themes = $this->getTheme()) {
45 ✔
603
            foreach ($themes as $theme) {
7 ✔
604
                if (!Util\File::getFS()->exists($this->getThemeDirPath($theme, 'layouts')) && !Util\File::getFS()->exists(Util::joinFile($this->getThemesPath(), $theme, 'config.yml'))) {
7 ✔
605
                    throw new ConfigException(\sprintf('Theme "%s" not found. Did you forgot to install it?', $theme));
2 ✔
606
                }
607
            }
608

609
            return true;
5 ✔
610
        }
611

612
        return false;
39 ✔
613
    }
614

615
    /**
616
     * Returns the path of a specific theme's directory.
617
     * ("layouts" by default).
618
     */
619
    public function getThemeDirPath(string $theme, string $dir = 'layouts'): string
620
    {
621
        return Util::joinFile($this->getThemesPath(), $theme, $dir);
22 ✔
622
    }
623

624
    /*
625
     * Language helpers.
626
     */
627

628
    /**
629
     * Returns an array of available languages.
630
     *
631
     * @return array<int, array<string, mixed>>
632
     *
633
     * @throws ConfigException
634
     */
635
    public function getLanguages(): array
636
    {
637
        if ($this->languages !== null) {
66 ✔
638
            return $this->languages;
43 ✔
639
        }
640
        $languages = array_filter((array) $this->get('languages'), function ($language) {
66 ✔
641
            return !(isset($language['enabled']) && $language['enabled'] === false);
66 ✔
642
        });
66 ✔
643
        if (!\is_int(array_search($this->getLanguageDefault(), array_column($languages, 'code')))) {
66 ✔
644
            throw new ConfigException(\sprintf('The default language "%s" is not listed in "languages".', $this->getLanguageDefault()));
2 ✔
645
        }
646
        $this->languages = $languages;
64 ✔
647

648
        return $this->languages;
64 ✔
649
    }
650

651
    /**
652
     * Returns the default language code (ie: "en", "fr-FR", etc.).
653
     *
654
     * @throws ConfigException
655
     */
656
    public function getLanguageDefault(): string
657
    {
658
        if (!$this->get('language')) {
375 ✔
659
            throw new ConfigException('There is no default "language" key.');
2 ✔
660
        }
661
        if (\is_array($this->get('language'))) {
374 ✔
662
            if (!$this->get('language.code')) {
1 ✔
663
                throw new ConfigException('There is no "language.code" key.');
×
664
            }
665

666
            return $this->get('language.code');
1 ✔
667
        }
668

669
        return $this->get('language');
373 ✔
670
    }
671

672
    /**
673
     * Returns a language code index.
674
     *
675
     * @throws ConfigException
676
     */
677
    public function getLanguageIndex(string $code): int
678
    {
679
        $array = array_column($this->getLanguages(), 'code');
4 ✔
680
        if (false === $index = array_search($code, $array)) {
4 ✔
681
            throw new ConfigException(\sprintf('The language code "%s" is not defined.', $code));
1 ✔
682
        }
683

684
        return $index;
3 ✔
685
    }
686

687
    /**
688
     * Returns the index of a language code in the `languages` configuration (disabled languages included),
689
     * used to read its localized configuration (`languages.<index>.config`).
690
     *
691
     * @throws ConfigException
692
     */
693
    private function getLanguageConfigIndex(string $code): int
694
    {
695
        // enabled languages, indexed by their position in the `languages` configuration
696
        foreach ($this->getLanguages() as $index => $language) {
20 ✔
697
            if (($language['code'] ?? null) === $code) {
20 ✔
698
                return $index;
20 ✔
699
            }
700
        }
701

NEW
702
        throw new ConfigException(\sprintf('The language code "%s" is not defined.', $code));
×
703
    }
704

705
    /**
706
     * Returns the localized configuration keys that are ignored (see `NOT_LOCALIZABLE_KEYS`), indexed by language code.
707
     *
708
     * @return array<string, list<string>>
709
     */
710
    public function getIgnoredLocalizedKeys(): array
711
    {
712
        $ignored = [];
14 ✔
713
        foreach ((array) $this->get('languages') as $index => $language) {
14 ✔
714
            if (!\is_array($language) || !isset($language['code']) || !\is_array($language['config'] ?? null)) {
14 ✔
715
                continue;
14 ✔
716
            }
717
            foreach (self::NOT_LOCALIZABLE_KEYS as $key) {
2 ✔
718
                if ($this->hasData("languages.$index.config.$key")) {
2 ✔
719
                    $ignored[(string) $language['code']][] = $key;
1 ✔
720
                }
721
            }
722
        }
723

724
        return $ignored;
14 ✔
725
    }
726

727
    /**
728
     * Returns the property value of a (specified or the default) language.
729
     *
730
     * @throws ConfigException
731
     */
732
    public function getLanguageProperty(string $property, ?string $code = null): string
733
    {
734
        $code = $code ?? $this->getLanguageDefault();
37 ✔
735
        $properties = array_column($this->getLanguages(), $property, 'code');
37 ✔
736
        if (empty($properties)) {
37 ✔
737
            throw new ConfigException(\sprintf('Property "%s" is not defined for language "%s".', $property, $code));
1 ✔
738
        }
739

740
        return $properties[$code];
36 ✔
741
    }
742

743
    /*
744
     * Cache helpers.
745
     */
746

747
    /**
748
     * Is cache dir is absolute to system files
749
     * or relative to project destination?
750
     */
751
    public function isCacheDirIsAbsolute(): bool
752
    {
753
        $path = (string) $this->get('cache.dir');
112 ✔
754
        if (Util\File::getFS()->isAbsolutePath($path)) {
112 ✔
755
            return true;
1 ✔
756
        }
757

758
        return false;
111 ✔
759
    }
760

761
    /*
762
     * Private functions.
763
     */
764

765
    /**
766
     * Returns the default value of a configuration key, if any.
767
     */
768
    private function getDefault(string $key): mixed
769
    {
770
        try {
771
            return $this->default->has($key) ? $this->default->get($key) : null;
3 ✔
772
        } catch (DataException) {
×
773
            return null;
×
774
        }
775
    }
776

777
    /**
778
     * Set configuration from environment variables starting with "CECIL_".
779
     */
780
    private function setFromEnv(): void
781
    {
782
        foreach ($this->getEnvConfig() as $key => $value) {
362 ✔
783
            $current = $this->data->has($key) ? $this->data->get($key) : null;
7 ✔
784
            $this->data->set($key, Merger::mergeValues($current, $value, self::IMPORT_REPLACE, $key));
7 ✔
785
        }
786
    }
787

788
    /**
789
     * Returns configuration from environment variables starting with "CECIL_", indexed by configuration key
790
     * (ie: `CECIL_PAGES_DIR` -> `pages.dir`).
791
     *
792
     * @return array<string, mixed>
793
     */
794
    private function getEnvConfig(): array
795
    {
796
        $config = [];
363 ✔
797
        foreach (array_merge(getenv() ?: [], $_ENV) as $key => $value) {
363 ✔
798
            if (str_starts_with((string) $key, 'CECIL_')) {
363 ✔
799
                $configKey = str_replace(['cecil_', '_'], ['', '.'], strtolower((string) $key));
8 ✔
800
                $config[$configKey] = $this->castSetValue($value, $configKey);
8 ✔
801
            }
802
        }
803

804
        return $config;
363 ✔
805
    }
806

807
    /**
808
     * Casts a value given as string (ie: by an environment variable), according to the default value of the key:
809
     * - to a number, if the default value is a number;
810
     * - to a boolean, if possible;
811
     * - to a number, if the default value is null (ie: `cache.assets.ttl`).
812
     *
813
     * @param mixed $value
814
     *
815
     * @return bool|int|float|mixed
816
     */
817
    private function castSetValue($value, ?string $key = null)
818
    {
819
        $defaultType = $key !== null ? $this->getDefaultType($key) : null;
8 ✔
820
        $isNumeric = \is_string($value) && is_numeric($value);
8 ✔
821

822
        if ($defaultType === 'number' && $isNumeric) {
8 ✔
823
            return self::toNumber($value);
1 ✔
824
        }
825

826
        $filteredValue = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
8 ✔
827

828
        if ($filteredValue !== null) {
8 ✔
829
            return $filteredValue;
5 ✔
830
        }
831

832
        if ($defaultType === 'null' && $isNumeric) {
5 ✔
833
            return self::toNumber($value);
1 ✔
834
        }
835

836
        return $value;
5 ✔
837
    }
838

839
    /**
840
     * Returns the type of the default value of a configuration key (`number`, `null` or `other`),
841
     * or null if the key doesn't exist in the default configuration.
842
     */
843
    private function getDefaultType(string $key): ?string
844
    {
845
        try {
846
            if (!$this->default->has($key)) {
8 ✔
847
                return null;
8 ✔
848
            }
NEW
849
        } catch (DataException) {
×
NEW
850
            return null;
×
851
        }
852
        $default = $this->default->get($key);
7 ✔
853

854
        return match (true) {
7 ✔
855
            $default === null                       => 'null',
2 ✔
856
            \is_int($default) || \is_float($default) => 'number',
6 ✔
857
            default                                 => 'other',
7 ✔
858
        };
7 ✔
859
    }
860

861
    /**
862
     * Converts a numeric string to an integer or a float.
863
     */
864
    private static function toNumber(string $value): int|float
865
    {
866
        return preg_match('/^-?\d+$/', $value) ? (int) $value : (float) $value;
1 ✔
867
    }
868

869
    /**
870
     * Validate the configuration.
871
     *
872
     * @throws ConfigException
873
     */
874
    private function validate(): void
875
    {
876
        // structural validation of well-defined sections
877
        $this->validateSchema();
362 ✔
878

879
        // default language must be valid
880
        if (!preg_match('/^' . Config::LANG_CODE_PATTERN . '$/', $this->getLanguageDefault())) {
341 ✔
881
            throw new ConfigException(\sprintf('Default language code "%s" is not valid (e.g.: "language: fr-FR").', $this->getLanguageDefault()));
1 ✔
882
        }
883
    }
884

885
    /**
886
     * Validates well-defined configuration sections against a schema.
887
     * Only targeted sections are processed: the rest of the configuration stays open
888
     * (menus, taxonomies, custom variables, etc.).
889
     *
890
     * @throws ConfigException
891
     */
892
    private function validateSchema(): void
893
    {
894
        $processor = new Processor();
362 ✔
895
        $schemas = $this->getSchemas();
362 ✔
896
        foreach ($schemas as $key => $schema) {
362 ✔
897
            if (!$this->has($key)) {
362 ✔
898
                continue;
341 ✔
899
            }
900
            try {
901
                $processor->process($schema, $this->get($key));
362 ✔
902
            } catch (ValidationException $e) {
21 ✔
903
                throw new ConfigException(self::schemaErrorMessage($key, $e), previous: $e);
21 ✔
904
            }
905
        }
906
        // localized configuration: the effective value of each language (global value overridden by the localized one) is validated
907
        foreach ((array) $this->get('languages') as $index => $language) {
342 ✔
908
            if (!\is_array($language) || !\is_array($language['config'] ?? null)) {
342 ✔
909
                continue;
339 ✔
910
            }
911
            foreach ($schemas as $key => $schema) {
10 ✔
912
                $keyLang = "languages.$index.config.$key";
10 ✔
913
                if (!$this->hasData($keyLang)) {
10 ✔
914
                    continue;
10 ✔
915
                }
916
                $value = $this->get($key);
8 ✔
917
                $localized = $this->data->get($keyLang);
8 ✔
918
                try {
919
                    $processor->process($schema, $value === null ? $localized : Merger::mergeValues($value, $localized, self::IMPORT_REPLACE, $key));
8 ✔
920
                } catch (ValidationException $e) {
1 ✔
921
                    throw new ConfigException(self::schemaErrorMessage($keyLang, $e), previous: $e);
1 ✔
922
                }
923
            }
924
        }
925
    }
926

927
    /**
928
     * Is the key exists in the effective configuration (false if a parent key is not an array)?
929
     */
930
    private function hasData(string $key): bool
931
    {
932
        try {
933
            return $this->data->has($key);
10 ✔
NEW
934
        } catch (DataException) {
×
NEW
935
            return false;
×
936
        }
937
    }
938

939
    /**
940
     * Returns the message of a schema validation error, with the path of each item from the root of the configuration.
941
     */
942
    private static function schemaErrorMessage(string $key, ValidationException $e): string
943
    {
944
        $messages = [];
22 ✔
945
        foreach ($e->getMessageObjects() as $message) {
22 ✔
946
            $message->path = array_merge(explode('.', $key), $message->path);
22 ✔
947
            if ($message->code === Message::FailedAssertion) {
22 ✔
948
                $messages[] = \sprintf("Invalid '%s': %s", implode("\u{a0}›\u{a0}", $message->path), $message->variables['assertion'] ?? '');
5 ✔
949
                continue;
5 ✔
950
            }
951
            $messages[] = $message->toString();
17 ✔
952
        }
953

954
        return implode("\n", $messages);
22 ✔
955
    }
956

957
    /**
958
     * Returns the validation schemas indexed by configuration key.
959
     *
960
     * @return array<string, Schema>
961
     */
962
    private function getSchemas(): array
963
    {
964
        return [
362 ✔
965
            // main site options
966
            'title'        => Expect::string(),
362 ✔
967
            'baseline'     => Expect::string(),
362 ✔
968
            'baseurl'      => Expect::string(),
362 ✔
969
            'canonicalurl' => Expect::bool(),
362 ✔
970
            'description'  => Expect::string(),
362 ✔
971
            // `theme: <name>` shorthand or a list of theme names
972
            'theme' => Expect::anyOf(
362 ✔
973
                Expect::string(),
362 ✔
974
                Expect::listOf('string')
362 ✔
975
            ),
362 ✔
976
            // `cache: true|false` shorthand or a structure with a non-empty `dir` when enabled
977
            'cache' => Expect::anyOf(
362 ✔
978
                Expect::bool(),
362 ✔
979
                self::open([
362 ✔
980
                    'enabled' => Expect::bool(),
362 ✔
981
                    'dir'     => Expect::string(),
362 ✔
982
                    'assets'  => self::open([
362 ✔
983
                        'ttl'    => Expect::int()->nullable(),
362 ✔
984
                        'remote' => self::open([
362 ✔
985
                            'ttl' => Expect::int()->nullable(),
362 ✔
986
                        ]),
362 ✔
987
                    ]),
362 ✔
988
                    'templates'    => self::toggle(),
362 ✔
989
                    'translations' => self::toggle(),
362 ✔
990
                ])->assert(
362 ✔
991
                    fn ($cache) => $cache->enabled === false || trim((string) ($cache->dir ?? '')) !== '',
362 ✔
992
                    'The cache directory (`cache.dir`) must not be empty when cache is enabled.'
362 ✔
993
                )
362 ✔
994
            ),
362 ✔
995
            // extensions loading options (entries of extensions maps are validated by the extensions loader, according to `extensions.strict`)
996
            'extensions' => self::open([
362 ✔
997
                'strict'      => Expect::bool()->nullable(),
362 ✔
998
                'autoload'    => Expect::arrayOf(Expect::string(), Expect::string()),
362 ✔
999
                'subscribers' => Expect::array(),
362 ✔
1000
                'plugins'     => Expect::array(),
362 ✔
1001
            ]),
362 ✔
1002
            // output directory and post processors
1003
            'output.dir'            => Expect::string(),
362 ✔
1004
            'output.postprocessors' => Expect::array(),
362 ✔
1005
            // each output format must define a unique `name` and a `mediatype`
1006
            'output.formats' => Expect::arrayOf(
362 ✔
1007
                self::open([
362 ✔
1008
                    'name'      => Expect::string()->required()->assert(fn ($value) => trim((string) $value) !== '', 'Output format "name" must not be empty.'),
362 ✔
1009
                    'mediatype' => Expect::string()->required()->assert(fn ($value) => trim((string) $value) !== '', 'Output format "mediatype" must not be empty.'),
362 ✔
1010
                    'rel'       => Expect::string(),
362 ✔
1011
                    'subpath'   => Expect::string(),
362 ✔
1012
                    'filename'  => Expect::string(),
362 ✔
1013
                    'extension' => Expect::string(),
362 ✔
1014
                    'exclude'   => Expect::listOf('string'),
362 ✔
1015
                ])
362 ✔
1016
            )->assert(
362 ✔
1017
                fn (array $formats) => self::hasUniqueValues($formats, 'name'),
362 ✔
1018
                'Output formats names must be unique.'
362 ✔
1019
            ),
362 ✔
1020
            // formats applied by page type (each type accepts a list of format names)
1021
            'output.pagetypeformats' => self::open([
362 ✔
1022
                'page'       => Expect::listOf('string'),
362 ✔
1023
                'homepage'   => Expect::listOf('string'),
362 ✔
1024
                'section'    => Expect::listOf('string'),
362 ✔
1025
                'vocabulary' => Expect::listOf('string'),
362 ✔
1026
                'term'       => Expect::listOf('string'),
362 ✔
1027
            ]),
362 ✔
1028
            // main language: `language: <code>` shorthand or a structure (a missing or invalid code is reported by `validate()`)
1029
            'language' => Expect::anyOf(
362 ✔
1030
                Expect::scalar(),
362 ✔
1031
                self::open([
362 ✔
1032
                    'code'   => Expect::string(),
362 ✔
1033
                    'prefix' => Expect::bool(),
362 ✔
1034
                ])
362 ✔
1035
            ),
362 ✔
1036
            // each language must define a valid `code` and a valid `locale` (duplicate codes are reported by the site doctor)
1037
            'languages' => Expect::listOf(
362 ✔
1038
                self::open([
362 ✔
1039
                    'code'    => Expect::string()->required()->pattern(Config::LANG_CODE_PATTERN),
362 ✔
1040
                    'name'    => Expect::string(),
362 ✔
1041
                    'locale'  => Expect::string()->required()->pattern(Config::LANG_LOCALE_PATTERN),
362 ✔
1042
                    'enabled' => Expect::bool(),
362 ✔
1043
                ])
362 ✔
1044
            ),
362 ✔
1045
            // date formatting options
1046
            'date' => self::open([
362 ✔
1047
                'format'   => Expect::string(),
362 ✔
1048
                'timezone' => Expect::string(),
362 ✔
1049
            ]),
362 ✔
1050
            // pages management options
1051
            'pages' => self::open([
362 ✔
1052
                'dir'    => Expect::string(),
362 ✔
1053
                'ext'    => Expect::listOf('string'),
362 ✔
1054
                'prefix' => self::open([
362 ✔
1055
                    'separator' => Expect::listOf('string'),
362 ✔
1056
                ]),
362 ✔
1057
                'exclude' => Expect::listOf('string'),
362 ✔
1058
                // `sortby: <variable>` shorthand or a structure
1059
                'sortby' => Expect::anyOf(
362 ✔
1060
                    Expect::string(),
362 ✔
1061
                    self::open([
362 ✔
1062
                        'variable'   => Expect::string(),
362 ✔
1063
                        'desc_title' => Expect::bool(),
362 ✔
1064
                        'reverse'    => Expect::bool(),
362 ✔
1065
                    ])
362 ✔
1066
                ),
362 ✔
1067
                'pagination' => self::toggle([
362 ✔
1068
                    'max'  => Expect::int()->min(1),
362 ✔
1069
                    'path' => Expect::string(),
362 ✔
1070
                ]),
362 ✔
1071
                'frontmatter' => Expect::anyOf('yaml', 'ini', 'toml', 'json'),
362 ✔
1072
                'converter'   => Expect::string(),
362 ✔
1073
                'body'        => self::open([
362 ✔
1074
                    'parser'    => Expect::string(),
362 ✔
1075
                    'toc'       => Expect::listOf('string'),
362 ✔
1076
                    'anchors'   => Expect::anyOf(Expect::bool(), Expect::listOf('string')),
362 ✔
1077
                    'highlight' => self::toggle([
362 ✔
1078
                        'engine' => Expect::string(),
362 ✔
1079
                    ]),
362 ✔
1080
                    'images' => self::open([
362 ✔
1081
                        'formats'            => Expect::listOf('string'),
362 ✔
1082
                        // a width in pixels (`0` to disable), a boolean is still accepted (legacy usage, ignored)
1083
                        'resize'             => Expect::anyOf(Expect::int()->min(0), Expect::bool()),
362 ✔
1084
                        'responsive'         => Expect::anyOf(Expect::bool(), 'width', 'density'),
362 ✔
1085
                        'lazy'               => Expect::bool(),
362 ✔
1086
                        'decoding'           => Expect::bool(),
362 ✔
1087
                        'caption'            => Expect::bool(),
362 ✔
1088
                        'placeholder'        => Expect::string(),
362 ✔
1089
                        'class'              => Expect::string(),
362 ✔
1090
                        'dark_suffix'        => Expect::string()->nullable(),
362 ✔
1091
                        'mobile_suffix'      => Expect::string()->nullable(),
362 ✔
1092
                        'mobile_media_query' => Expect::string(),
362 ✔
1093
                        'remote'             => self::toggle([
362 ✔
1094
                            'fallback' => Expect::string(),
362 ✔
1095
                        ]),
362 ✔
1096
                    ]),
362 ✔
1097
                    'links' => self::open([
362 ✔
1098
                        'embed' => self::toggle([
362 ✔
1099
                            'video' => Expect::listOf('string'),
362 ✔
1100
                            'audio' => Expect::listOf('string'),
362 ✔
1101
                        ]),
362 ✔
1102
                        'external' => self::open([
362 ✔
1103
                            'blank'      => Expect::bool(),
362 ✔
1104
                            'noopener'   => Expect::bool(),
362 ✔
1105
                            'noreferrer' => Expect::bool(),
362 ✔
1106
                            'nofollow'   => Expect::bool(),
362 ✔
1107
                        ]),
362 ✔
1108
                    ]),
362 ✔
1109
                    'excerpt' => self::open([
362 ✔
1110
                        'separator' => Expect::string(),
362 ✔
1111
                        'capture'   => Expect::anyOf('before', 'after'),
362 ✔
1112
                    ]),
362 ✔
1113
                ]),
362 ✔
1114
                'generators' => Expect::array(),
362 ✔
1115
            ]),
362 ✔
1116
            // default pages, indexed by ID: each published page must define a `path` (other keys are front matter variables)
1117
            'pages.default' => Expect::arrayOf(
362 ✔
1118
                Expect::structure([
362 ✔
1119
                    'path'         => Expect::anyOf(Expect::string(), Expect::int()),
362 ✔
1120
                    'published'    => Expect::bool(),
362 ✔
1121
                    'excluded'     => Expect::bool(),
362 ✔
1122
                    'exclude'      => Expect::bool(),
362 ✔
1123
                    'multilingual' => Expect::bool(),
362 ✔
1124
                    'uglyurl'      => Expect::bool(),
362 ✔
1125
                    'output'       => Expect::anyOf(Expect::string(), Expect::listOf('string')),
362 ✔
1126
                ])->otherItems(Expect::mixed())->assert(
362 ✔
1127
                    fn ($page) => $page->published === false || $page->path !== null,
362 ✔
1128
                    'A published default page must define a `path`.'
362 ✔
1129
                ),
362 ✔
1130
                Expect::anyOf(Expect::string(), Expect::int())
362 ✔
1131
            ),
362 ✔
1132
            // data files options
1133
            'data' => self::open([
362 ✔
1134
                'dir'  => Expect::string(),
362 ✔
1135
                'ext'  => Expect::listOf('string'),
362 ✔
1136
                'load' => Expect::bool(),
362 ✔
1137
            ]),
362 ✔
1138
            // assets options
1139
            'assets' => self::open([
362 ✔
1140
                'dir'         => Expect::string(),
362 ✔
1141
                'target'      => Expect::string(),
362 ✔
1142
                'fingerprint' => Expect::bool(),
362 ✔
1143
                'compile'     => self::open([
362 ✔
1144
                    'style' => Expect::string()->assert(
362 ✔
1145
                        fn ($value) => \in_array(strtolower((string) $value), ['expanded', 'compressed'], true),
362 ✔
1146
                        'The compilation style must be "expanded" or "compressed".'
362 ✔
1147
                    ),
362 ✔
1148
                    'import'    => Expect::listOf('string'),
362 ✔
1149
                    'sourcemap' => Expect::bool(),
362 ✔
1150
                    'variables' => Expect::array(),
362 ✔
1151
                ]),
362 ✔
1152
                'minify' => Expect::bool(),
362 ✔
1153
                'remote' => self::open([
362 ✔
1154
                    'useragent' => Expect::arrayOf(Expect::string(), Expect::string()),
362 ✔
1155
                    'timeout'   => Expect::int()->min(0),
362 ✔
1156
                ]),
362 ✔
1157
                'images' => self::open([
362 ✔
1158
                    'optimize'   => self::toggle(),
362 ✔
1159
                    'quality'    => Expect::int()->min(0)->max(100),
362 ✔
1160
                    'responsive' => self::open([
362 ✔
1161
                        'widths'    => Expect::listOf(Expect::int()->min(1)),
362 ✔
1162
                        'sizes'     => Expect::arrayOf(Expect::string(), Expect::string()),
362 ✔
1163
                        'densities' => Expect::listOf(Expect::type('int|float')->min(1)),
362 ✔
1164
                    ]),
362 ✔
1165
                    'cdn' => self::toggle([
362 ✔
1166
                        'url'       => Expect::string(),
362 ✔
1167
                        'svg'       => Expect::bool(),
362 ✔
1168
                        'remote'    => Expect::bool(),
362 ✔
1169
                        'account'   => Expect::string(),
362 ✔
1170
                        'canonical' => Expect::bool(),
362 ✔
1171
                    ]),
362 ✔
1172
                ]),
362 ✔
1173
            ]),
362 ✔
1174
            // static files options
1175
            'static' => self::open([
362 ✔
1176
                'dir'     => Expect::string(),
362 ✔
1177
                'target'  => Expect::string(),
362 ✔
1178
                'exclude' => Expect::listOf('string'),
362 ✔
1179
                'load'    => Expect::bool(),
362 ✔
1180
            ]),
362 ✔
1181
            // layouts and templates options
1182
            'layouts' => self::open([
362 ✔
1183
                'dir' => Expect::string(),
362 ✔
1184
                // `null` to use the template extension based strategy
1185
                'autoescape' => Expect::anyOf(Expect::bool(), Expect::string())->nullable(),
362 ✔
1186
                'images'     => self::open([
362 ✔
1187
                    'formats'            => Expect::listOf('string'),
362 ✔
1188
                    'responsive'         => Expect::anyOf(Expect::bool(), 'width', 'density'),
362 ✔
1189
                    'placeholder'        => Expect::string(),
362 ✔
1190
                    'dark_suffix'        => Expect::string()->nullable(),
362 ✔
1191
                    'mobile_suffix'      => Expect::string()->nullable(),
362 ✔
1192
                    'mobile_media_query' => Expect::string(),
362 ✔
1193
                ]),
362 ✔
1194
                'highlight' => self::open([
362 ✔
1195
                    'engine' => Expect::string(),
362 ✔
1196
                ]),
362 ✔
1197
                'translations' => self::open([
362 ✔
1198
                    'dir'     => Expect::string(),
362 ✔
1199
                    'formats' => Expect::arrayOf(
362 ✔
1200
                        self::open([
362 ✔
1201
                            'loader' => Expect::string(),
362 ✔
1202
                            'ext'    => Expect::listOf('string'),
362 ✔
1203
                        ]),
362 ✔
1204
                        Expect::string()
362 ✔
1205
                    ),
362 ✔
1206
                ]),
362 ✔
1207
                'extensions' => Expect::array(),
362 ✔
1208
                'components' => self::open([
362 ✔
1209
                    'dir' => Expect::string(),
362 ✔
1210
                    'ext' => Expect::string(),
362 ✔
1211
                ]),
362 ✔
1212
                'sections' => Expect::arrayOf(Expect::string(), Expect::string()),
362 ✔
1213
            ]),
362 ✔
1214
            // `optimize: true|false` shorthand or a structure enabling optimization by file type
1215
            'optimize' => self::toggle([
362 ✔
1216
                'html'   => self::toggle(['ext' => Expect::listOf('string')]),
362 ✔
1217
                'css'    => self::toggle(['ext' => Expect::listOf('string')]),
362 ✔
1218
                'js'     => self::toggle(['ext' => Expect::listOf('string')]),
362 ✔
1219
                'images' => self::toggle(['ext' => Expect::listOf('string')]),
362 ✔
1220
            ]),
362 ✔
1221
            // local preview server custom HTTP headers
1222
            'server.headers' => Expect::listOf(
362 ✔
1223
                self::open([
362 ✔
1224
                    'path'    => Expect::string()->required(),
362 ✔
1225
                    'headers' => Expect::listOf(
362 ✔
1226
                        self::open([
362 ✔
1227
                            'key'   => Expect::string()->required(),
362 ✔
1228
                            'value' => Expect::scalar()->required(),
362 ✔
1229
                        ])
362 ✔
1230
                    )->required(),
362 ✔
1231
                ])
362 ✔
1232
            ),
362 ✔
1233
        ];
362 ✔
1234
    }
1235

1236
    /**
1237
     * Returns an open structure schema: declared items are validated, other items are allowed.
1238
     *
1239
     * @param array<string, Schema> $items
1240
     */
1241
    private static function open(array $items): Structure
1242
    {
1243
        return Expect::structure($items)->otherItems(Expect::mixed());
362 ✔
1244
    }
1245

1246
    /**
1247
     * Returns the schema of an option that can be enabled or disabled:
1248
     * `<option>: true|false` shorthand, or an open structure with an `enabled` key and the given items.
1249
     *
1250
     * @param array<string, Schema> $items
1251
     */
1252
    private static function toggle(array $items = []): AnyOf
1253
    {
1254
        return Expect::anyOf(
362 ✔
1255
            Expect::bool(),
362 ✔
1256
            self::open(['enabled' => Expect::bool()] + $items)
362 ✔
1257
        );
362 ✔
1258
    }
1259

1260
    /**
1261
     * Checks that the items of a list (validated as structures) have unique values for the given key.
1262
     *
1263
     * @param array<int|string, object> $items
1264
     */
1265
    private static function hasUniqueValues(array $items, string $key): bool
1266
    {
1267
        $values = array_filter(array_column($items, $key), fn ($value) => $value !== null);
356 ✔
1268

1269
        return \count($values) === \count(array_unique($values));
356 ✔
1270
    }
1271
}
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