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

Cecilapp / Cecil / 7168486434

11 Dec 2023 01:57PM UTC coverage: 83.362% (+0.3%) from 83.077%
7168486434

push

github

ArnaudLigny
refactor: PHP 8 Exception

4 of 17 new or added lines in 8 files covered. (23.53%)

105 existing lines in 2 files now uncovered.

2866 of 3438 relevant lines covered (83.36%)

0.83 hits per line

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

77.91
/src/Config.php
1
<?php
2

3
declare(strict_types=1);
4

5
/*
6
 * This file is part of Cecil.
7
 *
8
 * Copyright (c) Arnaud Ligny <arnaud@ligny.fr>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13

14
namespace Cecil;
15

16
use Cecil\Exception\ConfigException;
17
use Cecil\Exception\RuntimeException;
18
use Cecil\Util\Plateform;
19
use Dflydev\DotAccessData\Data;
20

21
/**
22
 * Class Config.
23
 */
24
class Config
25
{
26
    /** @var Data Configuration is a Data object. */
27
    protected $data;
28

29
    /** @var array Configuration. */
30
    protected $siteConfig;
31

32
    /** @var string Source directory. */
33
    protected $sourceDir;
34

35
    /** @var string Destination directory. */
36
    protected $destinationDir;
37

38
    /** @var array Languages. */
39
    protected $languages = null;
40

41
    public const LANG_CODE_PATTERN = '([a-z]{2}(-[A-Z]{2})?)'; // "fr" or "fr-FR"
42
    public const LANG_LOCALE_PATTERN = '[a-z]{2}(_[A-Z]{2})?(_[A-Z]{2})?'; // "fr" or "fr_FR" or "no_NO_NY"
43

44
    /**
45
     * Build the Config object with the default config + the optional given array.
46
     */
47
    public function __construct(?array $config = null)
48
    {
49
        // load default configuration
50
        $defaultConfig = realpath(Util::joinFile(__DIR__, '..', 'config/default.php'));
1✔
51
        if (Plateform::isPhar()) {
1✔
52
            $defaultConfig = Util::joinPath(Plateform::getPharPath(), 'config/default.php');
×
53
        }
54
        $this->data = new Data(include $defaultConfig);
1✔
55

56
        // import site config
57
        $this->siteConfig = $config;
1✔
58
        $this->importSiteConfig();
1✔
59
    }
60

61
    /**
62
     * Imports site configuration.
63
     */
64
    private function importSiteConfig(): void
65
    {
66
        $this->data->import($this->siteConfig, Data::REPLACE);
1✔
67

68
        /**
69
         * Overrides configuration with environment variables.
70
         */
71
        $data = $this->getData();
1✔
72
        $applyEnv = function ($array) use ($data) {
1✔
73
            $iterator = new \RecursiveIteratorIterator(
1✔
74
                new \RecursiveArrayIterator($array),
1✔
75
                \RecursiveIteratorIterator::SELF_FIRST
1✔
76
            );
1✔
77
            $iterator->rewind();
1✔
78
            while ($iterator->valid()) {
1✔
79
                $path = [];
1✔
80
                foreach (range(0, $iterator->getDepth()) as $depth) {
1✔
81
                    $path[] = $iterator->getSubIterator($depth)->key();
1✔
82
                }
83
                $sPath = implode('_', $path);
1✔
84
                if ($getEnv = getenv('CECIL_' . strtoupper($sPath))) {
1✔
85
                    $data->set(str_replace('_', '.', strtolower($sPath)), $this->castSetValue($getEnv));
1✔
86
                }
87
                $iterator->next();
1✔
88
            }
89
        };
1✔
90
        $applyEnv($data->export());
1✔
91
    }
92

93
    /**
94
     * Casts boolean value given to set() as string.
95
     *
96
     * @param mixed $value
97
     *
98
     * @return bool|mixed
99
     */
100
    private function castSetValue($value)
101
    {
102
        if (\is_string($value)) {
1✔
103
            switch ($value) {
104
                case 'true':
1✔
105
                    return true;
1✔
106
                case 'false':
1✔
107
                    return false;
×
108
                default:
109
                    return $value;
1✔
110
            }
111
        }
112

113
        return $value;
×
114
    }
115

116
    /**
117
     * Imports (theme) configuration.
118
     */
119
    public function import(array $config): void
120
    {
121
        $this->data->import($config, Data::REPLACE);
1✔
122

123
        // re-import site config
124
        $this->importSiteConfig();
1✔
125

126
        // checks the configuration
127
        $this->valid();
1✔
128
    }
129

130
    /**
131
     * Get configuration as an array.
132
     */
133
    public function getAsArray(): array
134
    {
135
        return $this->data->export();
×
136
    }
137

138
    /**
139
     * Is configuration's key exists?
140
     */
141
    public function has(string $key): bool
142
    {
143
        return $this->data->has($key);
1✔
144
    }
145

146
    /**
147
     * Get the value of a configuration's key.
148
     *
149
     * @param string $key      Configuration key
150
     * @param string $language Language code (optionnal)
151
     * @param bool   $fallback Set to false to not return the value in the default language as fallback
152
     *
153
     * @return mixed|null
154
     */
155
    public function get(string $key, ?string $language = null, bool $fallback = true)
156
    {
157
        if ($language !== null) {
1✔
158
            $langIndex = $this->getLanguageIndex($language);
1✔
159
            $keyLang = "languages.$langIndex.config.$key";
1✔
160
            if ($this->data->has($keyLang)) {
1✔
161
                return $this->data->get($keyLang);
1✔
162
            }
163
            if ($language !== $this->getLanguageDefault() && $fallback === false) {
1✔
164
                return null;
1✔
165
            }
166
        }
167
        if ($this->data->has($key)) {
1✔
168
            return $this->data->get($key);
1✔
169
        }
170

171
        return null;
1✔
172
    }
173

174
    /**
175
     * Set the source directory.
176
     *
177
     * @throws \InvalidArgumentException
178
     */
179
    public function setSourceDir(string $sourceDir = null): self
180
    {
181
        if ($sourceDir === null) {
1✔
182
            $sourceDir = getcwd();
1✔
183
        }
184
        if (!is_dir($sourceDir)) {
1✔
185
            throw new \InvalidArgumentException(sprintf('The directory "%s" is not a valid source.', $sourceDir));
×
186
        }
187
        $this->sourceDir = $sourceDir;
1✔
188

189
        return $this;
1✔
190
    }
191

192
    /**
193
     * Get the source directory.
194
     */
195
    public function getSourceDir(): string
196
    {
197
        return $this->sourceDir;
1✔
198
    }
199

200
    /**
201
     * Set the destination directory.
202
     *
203
     * @throws \InvalidArgumentException
204
     */
205
    public function setDestinationDir(string $destinationDir = null): self
206
    {
207
        if ($destinationDir === null) {
1✔
208
            $destinationDir = $this->sourceDir;
1✔
209
        }
210
        if (!is_dir($destinationDir)) {
1✔
211
            throw new \InvalidArgumentException(sprintf('The directory "%s" is not a valid destination.', $destinationDir));
×
212
        }
213
        $this->destinationDir = $destinationDir;
1✔
214

215
        return $this;
1✔
216
    }
217

218
    /**
219
     * Get the destination directory.
220
     */
221
    public function getDestinationDir(): string
222
    {
223
        return $this->destinationDir;
1✔
224
    }
225

226
    /*
227
     * Path helpers.
228
     */
229

230
    /**
231
     * Returns the path of the pages directory.
232
     */
233
    public function getPagesPath(): string
234
    {
235
        return Util::joinFile($this->getSourceDir(), (string) $this->get('pages.dir'));
1✔
236
    }
237

238
    /**
239
     * Returns the path of the output directory.
240
     */
241
    public function getOutputPath(): string
242
    {
243
        return Util::joinFile($this->getDestinationDir(), (string) $this->get('output.dir'));
1✔
244
    }
245

246
    /**
247
     * Returns the path of the data directory.
248
     */
249
    public function getDataPath(): string
250
    {
251
        return Util::joinFile($this->getSourceDir(), (string) $this->get('data.dir'));
1✔
252
    }
253

254
    /**
255
     * Returns the path of templates directory.
256
     */
257
    public function getLayoutsPath(): string
258
    {
259
        return Util::joinFile($this->getSourceDir(), (string) $this->get('layouts.dir'));
1✔
260
    }
261

262
    /**
263
     * Returns the path of internal templates directory.
264
     */
265
    public function getLayoutsInternalPath(): string
266
    {
267
        return Util::joinPath(__DIR__, '..', (string) $this->get('layouts.internal.dir'));
1✔
268
    }
269

270
    /**
271
     * Returns the path of translations directory.
272
     */
273
    public function getTranslationsPath(): string
274
    {
275
        return Util::joinFile($this->getSourceDir(), (string) $this->get('layouts.translations.dir'));
1✔
276
    }
277

278
    /**
279
     * Returns the path of internal translations directory.
280
     */
281
    public function getTranslationsInternalPath(): string
282
    {
283
        if (Util\Plateform::isPhar()) {
1✔
UNCOV
284
            return Util::joinPath(Plateform::getPharPath(), (string) $this->get('layouts.translations.internal.dir'));
×
285
        }
286

287
        return realpath(Util::joinPath(__DIR__, '..', (string) $this->get('layouts.translations.internal.dir')));
1✔
288
    }
289

290
    /**
291
     * Returns the path of themes directory.
292
     */
293
    public function getThemesPath(): string
294
    {
295
        return Util::joinFile($this->getSourceDir(), (string) $this->get('themes.dir'));
1✔
296
    }
297

298
    /**
299
     * Returns the path of static files directory.
300
     */
301
    public function getStaticPath(): string
302
    {
303
        return Util::joinFile($this->getSourceDir(), (string) $this->get('static.dir'));
1✔
304
    }
305

306
    /**
307
     * Returns the path of static files directory, with a target.
308
     */
309
    public function getStaticTargetPath(): string
310
    {
311
        $path = $this->getStaticPath();
1✔
312

313
        if (!empty($this->get('static.target'))) {
1✔
UNCOV
314
            $path = substr($path, 0, -\strlen((string) $this->get('static.target')));
×
315
        }
316

317
        return $path;
1✔
318
    }
319

320
    /**
321
     * Returns the path of assets files directory.
322
     */
323
    public function getAssetsPath(): string
324
    {
325
        return Util::joinFile($this->getSourceDir(), (string) $this->get('assets.dir'));
1✔
326
    }
327

328
    /**
329
     * Returns cache path.
330
     *
331
     * @throws RuntimeException
332
     */
333
    public function getCachePath(): string
334
    {
335
        if (empty((string) $this->get('cache.dir'))) {
1✔
UNCOV
336
            throw new RuntimeException(sprintf('The cache directory ("%s") is not defined in configuration.', 'cache.dir'));
×
337
        }
338

339
        if ($this->isCacheDirIsAbsolute()) {
1✔
UNCOV
340
            $cacheDir = Util::joinFile((string) $this->get('cache.dir'), 'cecil');
×
UNCOV
341
            Util\File::getFS()->mkdir($cacheDir);
×
342

343
            return $cacheDir;
×
344
        }
345

346
        return Util::joinFile($this->getDestinationDir(), (string) $this->get('cache.dir'));
1✔
347
    }
348

349
    /**
350
     * Returns cache path of templates.
351
     */
352
    public function getCacheTemplatesPath(): string
353
    {
354
        return Util::joinFile($this->getCachePath(), (string) $this->get('cache.templates.dir'));
1✔
355
    }
356

357
    /**
358
     * Returns cache path of translations.
359
     */
360
    public function getCacheTranslationsPath(): string
361
    {
362
        return Util::joinFile($this->getCachePath(), (string) $this->get('cache.translations.dir'));
1✔
363
    }
364

365
    /**
366
     * Returns cache path of assets.
367
     */
368
    public function getCacheAssetsPath(): string
369
    {
370
        return Util::joinFile($this->getCachePath(), (string) $this->get('cache.assets.dir'));
1✔
371
    }
372

373
    /**
374
     * Returns cache path of remote assets.
375
     */
376
    public function getCacheAssetsRemotePath(): string
377
    {
378
        return Util::joinFile($this->getCacheAssetsPath(), (string) $this->get('cache.assets.remote.dir'));
1✔
379
    }
380

381
    /*
382
     * Output helpers.
383
     */
384

385
    /**
386
     * Returns the property value of an output format.
387
     *
388
     * @throws RuntimeException
389
     *
390
     * @return string|array|null
391
     */
392
    public function getOutputFormatProperty(string $name, string $property)
393
    {
394
        $properties = array_column((array) $this->get('output.formats'), $property, 'name');
1✔
395

396
        if (empty($properties)) {
1✔
UNCOV
397
            throw new RuntimeException(sprintf('Property "%s" is not defined for format "%s".', $property, $name));
×
398
        }
399

400
        return $properties[$name] ?? null;
1✔
401
    }
402

403
    /*
404
     * Assets helpers.
405
     */
406

407
    /**
408
     * Returns asset image widths.
409
     */
410
    public function getAssetsImagesWidths(): array
411
    {
412
        return \count((array) $this->get('assets.images.responsive.widths')) > 0 ? (array) $this->get('assets.images.responsive.widths') : [480, 640, 768, 1024, 1366, 1600, 1920];
1✔
413
    }
414

415
    /**
416
     * Returns asset image sizes.
417
     */
418
    public function getAssetsImagesSizes(): array
419
    {
420
        return \count((array) $this->get('assets.images.responsive.sizes')) > 0 ? (array) $this->get('assets.images.responsive.sizes') : ['default' => '100vw'];
1✔
421
    }
422

423
    /*
424
     * Theme helpers.
425
     */
426

427
    /**
428
     * Returns theme(s) as an array.
429
     */
430
    public function getTheme(): ?array
431
    {
432
        if ($themes = $this->get('theme')) {
1✔
433
            if (\is_array($themes)) {
1✔
434
                return $themes;
1✔
435
            }
436

UNCOV
437
            return [$themes];
×
438
        }
439

440
        return null;
×
441
    }
442

443
    /**
444
     * Has a (valid) theme(s)?
445
     *
446
     * @throws RuntimeException
447
     */
448
    public function hasTheme(): bool
449
    {
450
        if ($themes = $this->getTheme()) {
1✔
451
            foreach ($themes as $theme) {
1✔
452
                if (!Util\File::getFS()->exists($this->getThemeDirPath($theme, 'layouts')) && !Util\File::getFS()->exists(Util::joinFile($this->getThemesPath(), $theme, 'config.yml'))) {
1✔
UNCOV
453
                    throw new RuntimeException(sprintf('Theme "%s" not found. Did you forgot to install it?', $theme));
×
454
                }
455
            }
456

457
            return true;
1✔
458
        }
459

UNCOV
460
        return false;
×
461
    }
462

463
    /**
464
     * Returns the path of a specific theme's directory.
465
     * ("layouts" by default).
466
     */
467
    public function getThemeDirPath(string $theme, string $dir = 'layouts'): string
468
    {
469
        return Util::joinFile($this->getThemesPath(), $theme, $dir);
1✔
470
    }
471

472
    /*
473
     * Language helpers.
474
     */
475

476
    /**
477
     * Returns an array of available languages.
478
     *
479
     * @throws RuntimeException
480
     */
481
    public function getLanguages(): array
482
    {
483
        if ($this->languages !== null) {
1✔
484
            return $this->languages;
1✔
485
        }
486

487
        $languages = array_filter((array) $this->get('languages'), function ($language) {
1✔
488
            return !(isset($language['enabled']) && $language['enabled'] === false);
1✔
489
        });
1✔
490

491
        if (!\is_int(array_search($this->getLanguageDefault(), array_column($languages, 'code')))) {
1✔
UNCOV
492
            throw new RuntimeException(sprintf('The default language "%s" is not listed in "languages" key configuration.', $this->getLanguageDefault()));
×
493
        }
494

495
        $this->languages = $languages;
1✔
496

497
        return $this->languages;
1✔
498
    }
499

500
    /**
501
     * Returns the default language code (ie: "en", "fr-FR", etc.).
502
     *
503
     * @throws RuntimeException
504
     */
505
    public function getLanguageDefault(): string
506
    {
507
        if (!$this->get('language')) {
1✔
UNCOV
508
            throw new RuntimeException('There is no default "language" key in configuration.');
×
509
        }
510

511
        if ($this->get('language.code')) {
1✔
UNCOV
512
            return $this->get('language.code');
×
513
        }
514

515
        return $this->get('language');
1✔
516
    }
517

518
    /**
519
     * Returns a language code index.
520
     *
521
     * @throws RuntimeException
522
     */
523
    public function getLanguageIndex(string $code): int
524
    {
525
        $array = array_column($this->getLanguages(), 'code');
1✔
526

527
        if (false === $index = array_search($code, $array)) {
1✔
UNCOV
528
            throw new RuntimeException(sprintf('The language code "%s" is not defined.', $code));
×
529
        }
530

531
        return $index;
1✔
532
    }
533

534
    /**
535
     * Returns the property value of a (specified or the default) language.
536
     *
537
     * @throws RuntimeException
538
     */
539
    public function getLanguageProperty(string $property, ?string $code = null): string
540
    {
541
        $code = $code ?? $this->getLanguageDefault();
1✔
542

543
        $properties = array_column($this->getLanguages(), $property, 'code');
1✔
544

545
        if (empty($properties)) {
1✔
UNCOV
546
            throw new RuntimeException(sprintf('Property "%s" is not defined for language "%s".', $property, $code));
×
547
        }
548

549
        return $properties[$code];
1✔
550
    }
551

552
    /*
553
     * Cache helpers.
554
     */
555

556
    /**
557
     * Is cache dir is absolute to system files
558
     * or relative to project destination?
559
     */
560
    public function isCacheDirIsAbsolute(): bool
561
    {
562
        $path = (string) $this->get('cache.dir');
1✔
563
        if (Util::joinFile($path) == realpath(Util::joinFile($path))) {
1✔
UNCOV
564
            return true;
×
565
        }
566

567
        return false;
1✔
568
    }
569

570
    /**
571
     * Set a Data object as configuration.
572
     */
573
    protected function setData(Data $data): self
574
    {
UNCOV
575
        if ($this->data !== $data) {
×
UNCOV
576
            $this->data = $data;
×
577
        }
578

579
        return $this;
×
580
    }
581

582
    /**
583
     * Get configuration as a Data object.
584
     */
585
    protected function getData(): Data
586
    {
587
        return $this->data;
1✔
588
    }
589

590
    /**
591
     * Valid the configuration.
592
     */
593
    private function valid(): void
594
    {
595
        // default language must be valid
596
        if (!preg_match('/^' . Config::LANG_CODE_PATTERN . '$/', (string) $this->get('language'))) {
1✔
UNCOV
597
            throw new ConfigException(sprintf('Default language code "%s" is not valid (e.g.: "language: fr-FR").', $this->get('language')));
×
598
        }
599
        // if language is set then the locale is required
600
        foreach ((array) $this->get('languages') as $lang) {
1✔
601
            if (!isset($lang['locale'])) {
1✔
UNCOV
602
                throw new ConfigException('A language locale is not defined.');
×
603
            }
604
            if (!preg_match('/^' . Config::LANG_LOCALE_PATTERN . '$/', $lang['locale'])) {
1✔
605
                throw new ConfigException(sprintf('The language locale "%s" is not valid (e.g.: "locale: fr_FR").', $lang['locale']));
×
606
            }
607
        }
608
        // Version 8.x breaking changes
609
        $toV8 = [
1✔
610
            'frontmatter'  => 'pages:frontmatter',
1✔
611
            'body'         => 'pages:body',
1✔
612
            'defaultpages' => 'pages:default',
1✔
613
            'virtualpages' => 'pages:virtual',
1✔
614
            'generators'   => 'pages:generators',
1✔
615
            'translations' => 'layouts:translations',
1✔
616
            'extensions'   => 'layouts:extensions',
1✔
617
            'postprocess'  => 'optimize',
1✔
618
        ];
1✔
619
        array_walk($toV8, function ($to, $from) {
1✔
620
            if ($this->has($from)) {
1✔
UNCOV
621
                $path = explode(':', $to);
×
UNCOV
622
                $step = 0;
×
UNCOV
623
                $formatedPath = '';
×
624
                foreach ($path as $fragment) {
×
625
                    $step = $step + 2;
×
626
                    $formatedPath .= "$fragment:\n" . str_pad(' ', $step);
×
627
                }
628
                throw new ConfigException("Option `$from:` must be moved to:\n```\n$formatedPath\n```");
×
629
            }
630
        });
1✔
631
    }
632
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc