Passed
Push — cache ( 080d4e...9d0246 )
by Arnaud
04:24
created

Config::getLanguageIndex()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 9
ccs 2
cts 2
cp 1
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Cecil.
7
 *
8
 * Copyright (c) Arnaud Ligny <[email protected]>
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\Util\Platform;
18
use Dflydev\DotAccessData\Data;
19
20
/**
21
 * Class Config.
22
 */
23
class Config
24
{
25
    /** Configuration is a Data object. */
26
    protected Data $data;
27
28
    /** Default configuration is a Data object. */
29
    protected Data $default;
30
31
    /** Source directory. */
32
    protected string $sourceDir;
33
34
    /** Destination directory. */
35
    protected string $destinationDir;
36
37
    /** Languages list as array. */
38
    protected ?array $languages = null;
39
40
    public const PRESERVE = 0;
41
    public const REPLACE = 1;
42
    public const MERGE = 2;
43
    public const LANG_CODE_PATTERN = '([a-z]{2}(-[A-Z]{2})?)'; // "fr" or "fr-FR"
44
    public const LANG_LOCALE_PATTERN = '[a-z]{2}(_[A-Z]{2})?(_[A-Z]{2})?'; // "fr" or "fr_FR" or "no_NO_NY"
45
46
    /**
47
     * Build the Config object with the default config + the optional given array.
48
     */
49 1
    public function __construct(?array $config = null)
50
    {
51
        // default configuration
52 1
        $defaultConfigFile = realpath(Util::joinFile(__DIR__, '..', 'config/default.php'));
53 1
        if (Platform::isPhar()) {
54
            $defaultConfigFile = Util::joinPath(Platform::getPharPath(), 'config/default.php');
55
        }
56 1
        $this->default = new Data(include $defaultConfigFile);
57
58
        // base configuration
59 1
        $baseConfigFile = realpath(Util::joinFile(__DIR__, '..', 'config/base.php'));
60 1
        if (Platform::isPhar()) {
61
            $baseConfigFile = Util::joinPath(Platform::getPharPath(), 'config/base.php');
62
        }
63 1
        $this->data = new Data(include $baseConfigFile);
64
65
        // import config
66 1
        $this->import($config ?? []);
67
    }
68
69
    /**
70
     * Imports (and validate) configuration.
71
     */
72 1
    public function import(array $config, $mode = self::MERGE): void
73
    {
74 1
        $this->data->import($config, $mode);
75 1
        $this->setFromEnv();
76 1
        $this->validate();
77
    }
78
79
    /**
80
     * Get configuration as an array.
81
     */
82
    public function getAsArray(): array
83
    {
84
        return $this->data->export();
85
    }
86
87
    /**
88
     * Is configuration's key exists?
89
     *
90
     * @param string $key      Configuration key
91
     * @param string $language Language code (optional)
92
     * @param bool   $fallback Set to false to not return the value in the default language as fallback
93
     */
94 1
    public function has(string $key, ?string $language = null, bool $fallback = true): bool
95
    {
96 1
        $default = $this->default->has($key);
97
98 1
        if ($language !== null) {
99
            $langIndex = $this->getLanguageIndex($language);
100
            $keyLang = "languages.$langIndex.config.$key";
101
            if ($this->data->has($keyLang)) {
102
                return true;
103
            }
104
            if ($language !== $this->getLanguageDefault() && $fallback === false) {
105
                return $default;
106
            }
107
        }
108 1
        if ($this->data->has($key)) {
109 1
            return true;
110
        }
111
112 1
        return $default;
113
    }
114
115
    /**
116
     * Get the value of a configuration's key.
117
     *
118
     * @param string $key      Configuration key
119
     * @param string $language Language code (optional)
120
     * @param bool   $fallback Set to false to not return the value in the default language as fallback
121
     *
122
     * @return mixed|null
123
     */
124 1
    public function get(string $key, ?string $language = null, bool $fallback = true)
125
    {
126 1
        $default = $this->default->has($key) ? $this->default->get($key) : null;
127
128 1
        if ($language !== null) {
129 1
            $langIndex = $this->getLanguageIndex($language);
130 1
            $keyLang = "languages.$langIndex.config.$key";
131 1
            if ($this->data->has($keyLang)) {
132 1
                return $this->data->get($keyLang);
133
            }
134 1
            if ($language !== $this->getLanguageDefault() && $fallback === false) {
135 1
                return $default;
136
            }
137
        }
138 1
        if ($this->data->has($key)) {
139 1
            return $this->data->get($key);
140
        }
141
142 1
        return $default;
143
    }
144
145
    /**
146
     * Set the source directory.
147
     *
148
     * @throws \InvalidArgumentException
149
     */
150 1
    public function setSourceDir(?string $sourceDir = null): self
151
    {
152 1
        if ($sourceDir === null) {
153 1
            $sourceDir = getcwd();
154
        }
155 1
        if (!is_dir($sourceDir)) {
156
            throw new \InvalidArgumentException(\sprintf('The directory "%s" is not a valid source.', $sourceDir));
157
        }
158 1
        $this->sourceDir = $sourceDir;
159
160 1
        return $this;
161
    }
162
163
    /**
164
     * Get the source directory.
165
     */
166 1
    public function getSourceDir(): string
167
    {
168 1
        return $this->sourceDir;
169
    }
170
171
    /**
172
     * Set the destination directory.
173
     *
174
     * @throws \InvalidArgumentException
175
     */
176 1
    public function setDestinationDir(?string $destinationDir = null): self
177
    {
178 1
        if ($destinationDir === null) {
179 1
            $destinationDir = $this->sourceDir;
180
        }
181 1
        if (!is_dir($destinationDir)) {
182
            throw new \InvalidArgumentException(\sprintf('The directory "%s" is not a valid destination.', $destinationDir));
183
        }
184 1
        $this->destinationDir = $destinationDir;
185
186 1
        return $this;
187
    }
188
189
    /**
190
     * Get the destination directory.
191
     */
192 1
    public function getDestinationDir(): string
193
    {
194 1
        return $this->destinationDir;
195
    }
196
197
    /*
198
     * Path helpers.
199
     */
200
201
    /**
202
     * Returns the path of the pages directory.
203
     */
204 1
    public function getPagesPath(): string
205
    {
206 1
        return Util::joinFile($this->getSourceDir(), (string) $this->get('pages.dir'));
207
    }
208
209
    /**
210
     * Returns the path of the output directory.
211
     */
212 1
    public function getOutputPath(): string
213
    {
214 1
        return Util::joinFile($this->getDestinationDir(), (string) $this->get('output.dir'));
215
    }
216
217
    /**
218
     * Returns the path of the data directory.
219
     */
220 1
    public function getDataPath(): string
221
    {
222 1
        return Util::joinFile($this->getSourceDir(), (string) $this->get('data.dir'));
223
    }
224
225
    /**
226
     * Returns the path of templates directory.
227
     */
228 1
    public function getLayoutsPath(): string
229
    {
230 1
        return Util::joinFile($this->getSourceDir(), (string) $this->get('layouts.dir'));
231
    }
232
233
    /**
234
     * Returns the path of internal templates directory.
235
     */
236 1
    public function getLayoutsInternalPath(): string
237
    {
238 1
        return Util::joinPath(__DIR__, '..', (string) $this->get('layouts.internal.dir'));
239
    }
240
241
    /**
242
     * Returns the layout for a section.
243
     */
244 1
    public function getLayoutSection(?string $section): ?string
245
    {
246 1
        if ($layout = $this->get('layouts.sections')[$section] ?? null) {
247
            return $layout;
248
        }
249
250 1
        return $section;
251
    }
252
253
    /**
254
     * Returns the path of translations directory.
255
     */
256 1
    public function getTranslationsPath(): string
257
    {
258 1
        return Util::joinFile($this->getSourceDir(), (string) $this->get('layouts.translations.dir'));
259
    }
260
261
    /**
262
     * Returns the path of internal translations directory.
263
     */
264 1
    public function getTranslationsInternalPath(): string
265
    {
266 1
        if (Util\Platform::isPhar()) {
267
            return Util::joinPath(Platform::getPharPath(), (string) $this->get('layouts.translations.internal.dir'));
268
        }
269
270 1
        return realpath(Util::joinPath(__DIR__, '..', (string) $this->get('layouts.translations.internal.dir')));
271
    }
272
273
    /**
274
     * Returns the path of themes directory.
275
     */
276 1
    public function getThemesPath(): string
277
    {
278 1
        return Util::joinFile($this->getSourceDir(), (string) $this->get('themes.dir'));
279
    }
280
281
    /**
282
     * Returns the path of static files directory.
283
     */
284 1
    public function getStaticPath(): string
285
    {
286 1
        return Util::joinFile($this->getSourceDir(), (string) $this->get('static.dir'));
287
    }
288
289
    /**
290
     * Returns the path of static files directory, with a target.
291
     */
292 1
    public function getStaticTargetPath(): string
293
    {
294 1
        $path = $this->getStaticPath();
295
296 1
        if (!empty($this->get('static.target'))) {
297
            $path = substr($path, 0, -\strlen((string) $this->get('static.target')));
298
        }
299
300 1
        return $path;
301
    }
302
303
    /**
304
     * Returns the path of assets files directory.
305
     */
306 1
    public function getAssetsPath(): string
307
    {
308 1
        return Util::joinFile($this->getSourceDir(), (string) $this->get('assets.dir'));
309
    }
310
311
    /**
312
     * Returns the path of remote assets files directory (in cache).
313
     *
314
     * @return string
315
     */
316 1
    public function getAssetsRemotePath(): string
317
    {
318 1
        return Util::joinFile($this->getCacheAssetsPath(), (string) $this->get('assets.remote.dir'));
319
    }
320
321
    /**
322 1
     * Returns cache path.
323
     *
324
     * @throws ConfigException
325
     */
326
    public function getCachePath(): string
327
    {
328
        if (empty((string) $this->get('cache.dir'))) {
329 1
            throw new ConfigException(\sprintf('The cache directory ("%s") is not defined.', 'cache.dir'));
330
        }
331
332
        if ($this->isCacheDirIsAbsolute()) {
333
            $cacheDir = Util::joinFile((string) $this->get('cache.dir'), 'cecil');
334
            Util\File::getFS()->mkdir($cacheDir);
335 1
336
            return $cacheDir;
337 1
        }
338
339
        return Util::joinFile($this->getDestinationDir(), (string) $this->get('cache.dir'));
340
    }
341
342
    /**
343 1
     * Returns cache path of templates.
344
     */
345 1
    public function getCacheTemplatesPath(): string
346
    {
347
        return Util::joinFile($this->getCachePath(), (string) $this->get('cache.templates.dir'));
348
    }
349
350
    /**
351 1
     * Returns cache path of translations.
352
     */
353 1
    public function getCacheTranslationsPath(): string
354
    {
355
        return Util::joinFile($this->getCachePath(), (string) $this->get('cache.translations.dir'));
356
    }
357
358
    /**
359 1
     * Returns cache path of assets.
360
     */
361 1
    public function getCacheAssetsPath(): string
362
    {
363
        return Util::joinFile($this->getCachePath(), (string) $this->get('cache.assets.dir'));
364
    }
365
366
    /**
367
     * Returns cache path of assets files.
368
     */
369
    public function getCacheAssetsFilesPath(): string
370
    {
371
        return Util::joinFile($this->getCacheAssetsPath(), (string) $this->get('cache.assets.files.dir'));
372
    }
373 1
374
    /*
375 1
     * Output helpers.
376
     */
377 1
378
    /**
379
     * Returns the property value of an output format.
380
     *
381 1
     * @throws ConfigException
382
     */
383
    public function getOutputFormatProperty(string $name, string $property): string|array|null
384
    {
385
        $properties = array_column((array) $this->get('output.formats'), $property, 'name');
386
387
        if (empty($properties)) {
388
            throw new ConfigException(\sprintf('Property "%s" is not defined for format "%s".', $property, $name));
389
        }
390
391 1
        return $properties[$name] ?? null;
392
    }
393 1
394
    /*
395
     * Assets helpers.
396
     */
397
398
    /**
399 1
     * Returns asset image widths.
400
     */
401 1
    public function getAssetsImagesWidths(): array
402
    {
403
        return $this->get('assets.images.responsive.widths');
404
    }
405
406
    /**
407
     * Returns asset image sizes.
408
     */
409
    public function getAssetsImagesSizes(): array
410
    {
411 1
        return $this->get('assets.images.responsive.sizes');
412
    }
413 1
414 1
    /*
415 1
     * Theme helpers.
416
     */
417
418
    /**
419
     * Returns theme(s) as an array.
420
     */
421
    public function getTheme(): ?array
422
    {
423
        if ($themes = $this->get('theme')) {
424
            if (\is_array($themes)) {
425
                return $themes;
426
            }
427
428
            return [$themes];
429 1
        }
430
431 1
        return null;
432 1
    }
433 1
434
    /**
435
     * Has a (valid) theme(s)?
436
     *
437
     * @throws ConfigException
438 1
     */
439
    public function hasTheme(): bool
440
    {
441
        if ($themes = $this->getTheme()) {
442
            foreach ($themes as $theme) {
443
                if (!Util\File::getFS()->exists($this->getThemeDirPath($theme, 'layouts')) && !Util\File::getFS()->exists(Util::joinFile($this->getThemesPath(), $theme, 'config.yml'))) {
444
                    throw new ConfigException(\sprintf('Theme "%s" not found. Did you forgot to install it?', $theme));
445
                }
446
            }
447
448 1
            return true;
449
        }
450 1
451
        return false;
452
    }
453
454
    /**
455
     * Returns the path of a specific theme's directory.
456
     * ("layouts" by default).
457
     */
458
    public function getThemeDirPath(string $theme, string $dir = 'layouts'): string
459
    {
460
        return Util::joinFile($this->getThemesPath(), $theme, $dir);
461
    }
462 1
463
    /*
464 1
     * Language helpers.
465 1
     */
466
467
    /**
468 1
     * Returns an array of available languages.
469 1
     *
470 1
     * @throws ConfigException
471
     */
472 1
    public function getLanguages(): array
473
    {
474
        if ($this->languages !== null) {
475
            return $this->languages;
476 1
        }
477
478 1
        $languages = array_filter((array) $this->get('languages'), function ($language) {
479
            return !(isset($language['enabled']) && $language['enabled'] === false);
480
        });
481
482
        if (!\is_int(array_search($this->getLanguageDefault(), array_column($languages, 'code')))) {
483
            throw new ConfigException(\sprintf('The default language "%s" is not listed in "languages".', $this->getLanguageDefault()));
484
        }
485
486 1
        $this->languages = $languages;
487
488 1
        return $this->languages;
489
    }
490
491 1
    /**
492
     * Returns the default language code (ie: "en", "fr-FR", etc.).
493
     *
494
     * @throws ConfigException
495
     */
496
    public function getLanguageDefault(): string
497
    {
498
        if (!$this->get('language')) {
499 1
            throw new ConfigException('There is no default "language" key.');
500
        }
501
        if (\is_array($this->get('language'))) {
502
            if (!$this->get('language.code')) {
503
                throw new ConfigException('There is no "language.code" key.');
504
            }
505
506
            return $this->get('language.code');
507 1
        }
508
509 1
        return $this->get('language');
510
    }
511 1
512
    /**
513
     * Returns a language code index.
514
     *
515 1
     * @throws ConfigException
516
     */
517
    public function getLanguageIndex(string $code): int
518
    {
519
        $array = array_column($this->getLanguages(), 'code');
520
521
        if (false === $index = array_search($code, $array)) {
522
            throw new ConfigException(\sprintf('The language code "%s" is not defined.', $code));
523 1
        }
524
525 1
        return $index;
526
    }
527 1
528
    /**
529 1
     * Returns the property value of a (specified or the default) language.
530
     *
531
     * @throws ConfigException
532
     */
533 1
    public function getLanguageProperty(string $property, ?string $code = null): string
534
    {
535
        $code = $code ?? $this->getLanguageDefault();
536
537
        $properties = array_column($this->getLanguages(), $property, 'code');
538
539
        if (empty($properties)) {
540
            throw new ConfigException(\sprintf('Property "%s" is not defined for language "%s".', $property, $code));
541
        }
542
543
        return $properties[$code];
544 1
    }
545
546 1
    /*
547 1
     * Cache helpers.
548
     */
549
550
    /**
551 1
     * Is cache dir is absolute to system files
552
     * or relative to project destination?
553
     */
554
    public function isCacheDirIsAbsolute(): bool
555
    {
556
        $path = (string) $this->get('cache.dir');
557 1
        if (Util::joinFile($path) == realpath(Util::joinFile($path))) {
558
            return true;
559 1
        }
560 1
561 1
        return false;
562
    }
563
564
    /**
565
     * Set configuration from environment variables.
566
     */
567
    private function setFromEnv(): void
568
    {
569
        foreach (getenv() as $key => $value) {
570
            if (str_starts_with($key, 'CECIL_')) {
571
                $this->data->set(str_replace(['cecil_', '_'], ['', '.'], strtolower($key)), $this->castSetValue($value));
572
            }
573 1
        }
574
    }
575 1
576
    /**
577 1
     * Casts boolean value given to set() as string.
578 1
     *
579
     * @param mixed $value
580
     *
581 1
     * @return bool|mixed
582
     */
583
    private function castSetValue($value)
584
    {
585
        $filteredValue = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
586
587
        if ($filteredValue !== null) {
588
            return $filteredValue;
589 1
        }
590
591
        return $value;
592 1
    }
593
594
    /**
595
     * Validate the configuration.
596 1
     *
597 1
     * @throws ConfigException
598
     */
599
    private function validate(): void
600 1
    {
601
        // default language must be valid
602
        if (!preg_match('/^' . Config::LANG_CODE_PATTERN . '$/', $this->getLanguageDefault())) {
603
            throw new ConfigException(\sprintf('Default language code "%s" is not valid (e.g.: "language: fr-FR").', $this->getLanguageDefault()));
604
        }
605
        // if language is set then the locale is required and must be valid
606 1
        foreach ((array) $this->get('languages') as $lang) {
607 1
            if (!isset($lang['locale'])) {
608 1
                throw new ConfigException('A language locale is not defined.');
609 1
            }
610 1
            if (!preg_match('/^' . Config::LANG_LOCALE_PATTERN . '$/', $lang['locale'])) {
611 1
                throw new ConfigException(\sprintf('The language locale "%s" is not valid (e.g.: "locale: fr_FR").', $lang['locale']));
612 1
            }
613 1
        }
614 1
615 1
        // version 8.x breaking changes detection
616 1
        $toV8 = [
617 1
            'frontmatter'  => 'pages:frontmatter',
618
            'body'         => 'pages:body',
619
            'defaultpages' => 'pages:default',
620
            'virtualpages' => 'pages:virtual',
621
            'generators'   => 'pages:generators',
622
            'translations' => 'layouts:translations',
623
            'extensions'   => 'layouts:extensions',
624
            'postprocess'  => 'optimize',
625
        ];
626
        array_walk($toV8, function ($to, $from) {
627 1
            if ($this->has($from)) {
628
                $path = explode(':', $to);
629
                $step = 0;
630
                $formatedPath = '';
631
                foreach ($path as $fragment) {
632
                    $step = $step + 2;
633
                    $formatedPath .= "$fragment:\n" . str_pad(' ', $step);
634
                }
635
                throw new ConfigException("Option `$from:` must be moved to:\n```\n$formatedPath\n```");
636
            }
637
        });
638
    }
639
}
640