Passed
Pull Request — master (#2068)
by Arnaud
10:00 queued 04:29
created

Config::get()   B

Complexity

Conditions 7
Paths 12

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 7

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 7
eloc 11
nc 12
nop 3
dl 0
loc 19
ccs 12
cts 12
cp 1
crap 7
rs 8.8333
c 1
b 0
f 1
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\Plateform;
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 (Plateform::isPhar()) {
54
            $defaultConfigFile = Util::joinPath(Plateform::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 (Plateform::isPhar()) {
61
            $baseConfigFile = Util::joinPath(Plateform::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->validate();
76 1
        $this->override();
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 path of translations directory.
243
     */
244 1
    public function getTranslationsPath(): string
245
    {
246 1
        return Util::joinFile($this->getSourceDir(), (string) $this->get('layouts.translations.dir'));
247
    }
248
249
    /**
250
     * Returns the path of internal translations directory.
251
     */
252 1
    public function getTranslationsInternalPath(): string
253
    {
254 1
        if (Util\Plateform::isPhar()) {
255
            return Util::joinPath(Plateform::getPharPath(), (string) $this->get('layouts.translations.internal.dir'));
256
        }
257
258 1
        return realpath(Util::joinPath(__DIR__, '..', (string) $this->get('layouts.translations.internal.dir')));
259
    }
260
261
    /**
262
     * Returns the path of themes directory.
263
     */
264 1
    public function getThemesPath(): string
265
    {
266 1
        return Util::joinFile($this->getSourceDir(), (string) $this->get('themes.dir'));
267
    }
268
269
    /**
270
     * Returns the path of static files directory.
271
     */
272 1
    public function getStaticPath(): string
273
    {
274 1
        return Util::joinFile($this->getSourceDir(), (string) $this->get('static.dir'));
275
    }
276
277
    /**
278
     * Returns the path of static files directory, with a target.
279
     */
280 1
    public function getStaticTargetPath(): string
281
    {
282 1
        $path = $this->getStaticPath();
283
284 1
        if (!empty($this->get('static.target'))) {
285
            $path = substr($path, 0, -\strlen((string) $this->get('static.target')));
286
        }
287
288 1
        return $path;
289
    }
290
291
    /**
292
     * Returns the path of assets files directory.
293
     */
294 1
    public function getAssetsPath(): string
295
    {
296 1
        return Util::joinFile($this->getSourceDir(), (string) $this->get('assets.dir'));
297
    }
298
299
    /**
300
     * Returns cache path.
301
     *
302
     * @throws ConfigException
303
     */
304 1
    public function getCachePath(): string
305
    {
306 1
        if (empty((string) $this->get('cache.dir'))) {
307
            throw new ConfigException(\sprintf('The cache directory ("%s") is not defined.', 'cache.dir'));
308
        }
309
310 1
        if ($this->isCacheDirIsAbsolute()) {
311
            $cacheDir = Util::joinFile((string) $this->get('cache.dir'), 'cecil');
312
            Util\File::getFS()->mkdir($cacheDir);
313
314
            return $cacheDir;
315
        }
316
317 1
        return Util::joinFile($this->getDestinationDir(), (string) $this->get('cache.dir'));
318
    }
319
320
    /**
321
     * Returns cache path of templates.
322
     */
323 1
    public function getCacheTemplatesPath(): string
324
    {
325 1
        return Util::joinFile($this->getCachePath(), (string) $this->get('cache.templates.dir'));
326
    }
327
328
    /**
329
     * Returns cache path of translations.
330
     */
331 1
    public function getCacheTranslationsPath(): string
332
    {
333 1
        return Util::joinFile($this->getCachePath(), (string) $this->get('cache.translations.dir'));
334
    }
335
336
    /**
337
     * Returns cache path of assets.
338
     */
339 1
    public function getCacheAssetsPath(): string
340
    {
341 1
        return Util::joinFile($this->getCachePath(), (string) $this->get('cache.assets.dir'));
342
    }
343
344
    /**
345
     * Returns cache path of remote assets.
346
     */
347 1
    public function getCacheAssetsRemotePath(): string
348
    {
349 1
        return Util::joinFile($this->getCacheAssetsPath(), (string) $this->get('cache.assets.remote.dir'));
350
    }
351
352
    /*
353
     * Output helpers.
354
     */
355
356
    /**
357
     * Returns the property value of an output format.
358
     *
359
     * @throws ConfigException
360
     */
361 1
    public function getOutputFormatProperty(string $name, string $property): string|array|null
362
    {
363 1
        $properties = array_column((array) $this->get('output.formats'), $property, 'name');
364
365 1
        if (empty($properties)) {
366
            throw new ConfigException(\sprintf('Property "%s" is not defined for format "%s".', $property, $name));
367
        }
368
369 1
        return $properties[$name] ?? null;
370
    }
371
372
    /*
373
     * Assets helpers.
374
     */
375
376
    /**
377
     * Returns asset image widths.
378
     */
379 1
    public function getAssetsImagesWidths(): array
380
    {
381 1
        return $this->get('assets.images.responsive.widths');
382
    }
383
384
    /**
385
     * Returns asset image sizes.
386
     */
387 1
    public function getAssetsImagesSizes(): array
388
    {
389 1
        return $this->get('assets.images.responsive.sizes');
390
    }
391
392
    /*
393
     * Theme helpers.
394
     */
395
396
    /**
397
     * Returns theme(s) as an array.
398
     */
399 1
    public function getTheme(): ?array
400
    {
401 1
        if ($themes = $this->get('theme')) {
402 1
            if (\is_array($themes)) {
403 1
                return $themes;
404
            }
405
406
            return [$themes];
407
        }
408
409
        return null;
410
    }
411
412
    /**
413
     * Has a (valid) theme(s)?
414
     *
415
     * @throws ConfigException
416
     */
417 1
    public function hasTheme(): bool
418
    {
419 1
        if ($themes = $this->getTheme()) {
420 1
            foreach ($themes as $theme) {
421 1
                if (!Util\File::getFS()->exists($this->getThemeDirPath($theme, 'layouts')) && !Util\File::getFS()->exists(Util::joinFile($this->getThemesPath(), $theme, 'config.yml'))) {
422
                    throw new ConfigException(\sprintf('Theme "%s" not found. Did you forgot to install it?', $theme));
423
                }
424
            }
425
426 1
            return true;
427
        }
428
429
        return false;
430
    }
431
432
    /**
433
     * Returns the path of a specific theme's directory.
434
     * ("layouts" by default).
435
     */
436 1
    public function getThemeDirPath(string $theme, string $dir = 'layouts'): string
437
    {
438 1
        return Util::joinFile($this->getThemesPath(), $theme, $dir);
439
    }
440
441
    /*
442
     * Language helpers.
443
     */
444
445
    /**
446
     * Returns an array of available languages.
447
     *
448
     * @throws ConfigException
449
     */
450 1
    public function getLanguages(): array
451
    {
452 1
        if ($this->languages !== null) {
453 1
            return $this->languages;
454
        }
455
456 1
        $languages = array_filter((array) $this->get('languages'), function ($language) {
457 1
            return !(isset($language['enabled']) && $language['enabled'] === false);
458 1
        });
459
460 1
        if (!\is_int(array_search($this->getLanguageDefault(), array_column($languages, 'code')))) {
461
            throw new ConfigException(\sprintf('The default language "%s" is not listed in "languages".', $this->getLanguageDefault()));
462
        }
463
464 1
        $this->languages = $languages;
465
466 1
        return $this->languages;
467
    }
468
469
    /**
470
     * Returns the default language code (ie: "en", "fr-FR", etc.).
471
     *
472
     * @throws ConfigException
473
     */
474 1
    public function getLanguageDefault(): string
475
    {
476 1
        if (!$this->get('language')) {
477
            throw new ConfigException('There is no default "language" key.');
478
        }
479 1
        if (\is_array($this->get('language'))) {
480
            if (!$this->get('language.code')) {
481
                throw new ConfigException('There is no "language.code" key.');
482
            }
483
484
            return $this->get('language.code');
485
        }
486
487 1
        return $this->get('language');
488
    }
489
490
    /**
491
     * Returns a language code index.
492
     *
493
     * @throws ConfigException
494
     */
495 1
    public function getLanguageIndex(string $code): int
496
    {
497 1
        $array = array_column($this->getLanguages(), 'code');
498
499 1
        if (false === $index = array_search($code, $array)) {
500
            throw new ConfigException(\sprintf('The language code "%s" is not defined.', $code));
501
        }
502
503 1
        return $index;
504
    }
505
506
    /**
507
     * Returns the property value of a (specified or the default) language.
508
     *
509
     * @throws ConfigException
510
     */
511 1
    public function getLanguageProperty(string $property, ?string $code = null): string
512
    {
513 1
        $code = $code ?? $this->getLanguageDefault();
514
515 1
        $properties = array_column($this->getLanguages(), $property, 'code');
516
517 1
        if (empty($properties)) {
518
            throw new ConfigException(\sprintf('Property "%s" is not defined for language "%s".', $property, $code));
519
        }
520
521 1
        return $properties[$code];
522
    }
523
524
    /*
525
     * Cache helpers.
526
     */
527
528
    /**
529
     * Is cache dir is absolute to system files
530
     * or relative to project destination?
531
     */
532 1
    public function isCacheDirIsAbsolute(): bool
533
    {
534 1
        $path = (string) $this->get('cache.dir');
535 1
        if (Util::joinFile($path) == realpath(Util::joinFile($path))) {
536
            return true;
537
        }
538
539 1
        return false;
540
    }
541
542
    /**
543
     * Overrides configuration with environment variables.
544
     */
545 1
    private function override(): void
546
    {
547 1
        $data = $this->data;
548 1
        $applyEnv = function ($array) use ($data) {
549 1
            $iterator = new \RecursiveIteratorIterator(
550 1
                new \RecursiveArrayIterator($array),
551 1
                \RecursiveIteratorIterator::SELF_FIRST
552 1
            );
553 1
            $iterator->rewind();
554 1
            while ($iterator->valid()) {
555 1
                $path = [];
556 1
                foreach (range(0, $iterator->getDepth()) as $depth) {
557 1
                    $path[] = $iterator->getSubIterator($depth)->key();
558
                }
559 1
                $sPath = implode('_', $path);
560 1
                if ($getEnv = getenv('CECIL_' . strtoupper($sPath))) {
561 1
                    $data->set(str_replace('_', '.', strtolower($sPath)), $this->castSetValue($getEnv));
562
                }
563 1
                $iterator->next();
564
            }
565 1
        };
566 1
        $applyEnv($data->export());
567
    }
568
569
    /**
570
     * Casts boolean value given to set() as string.
571
     *
572
     * @param mixed $value
573
     *
574
     * @return bool|mixed
575
     */
576 1
    private function castSetValue($value)
577
    {
578 1
        $filteredValue = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
579
580 1
        if ($filteredValue !== null) {
581 1
            return $filteredValue;
582
        }
583
584 1
        return $value;
585
    }
586
587
    /**
588
     * Validate the configuration.
589
     *
590
     * @throws ConfigException
591
     */
592 1
    private function validate(): void
593
    {
594
        // default language must be valid
595 1
        if (!preg_match('/^' . Config::LANG_CODE_PATTERN . '$/', $this->getLanguageDefault())) {
596
            throw new ConfigException(\sprintf('Default language code "%s" is not valid (e.g.: "language: fr-FR").', $this->getLanguageDefault()));
597
        }
598
        // if language is set then the locale is required and must be valid
599 1
        foreach ((array) $this->get('languages') as $lang) {
600 1
            if (!isset($lang['locale'])) {
601
                throw new ConfigException('A language locale is not defined.');
602
            }
603 1
            if (!preg_match('/^' . Config::LANG_LOCALE_PATTERN . '$/', $lang['locale'])) {
604
                throw new ConfigException(\sprintf('The language locale "%s" is not valid (e.g.: "locale: fr_FR").', $lang['locale']));
605
            }
606
        }
607
608
        // version 8.x breaking changes detection
609 1
        $toV8 = [
610 1
            'frontmatter'  => 'pages:frontmatter',
611 1
            'body'         => 'pages:body',
612 1
            'defaultpages' => 'pages:default',
613 1
            'virtualpages' => 'pages:virtual',
614 1
            'generators'   => 'pages:generators',
615 1
            'translations' => 'layouts:translations',
616 1
            'extensions'   => 'layouts:extensions',
617 1
            'postprocess'  => 'optimize',
618 1
        ];
619 1
        array_walk($toV8, function ($to, $from) {
620 1
            if ($this->has($from)) {
621
                $path = explode(':', $to);
622
                $step = 0;
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
}
633