Passed
Pull Request — master (#2148)
by Arnaud
10:28 queued 04:55
created

Config::isEnabled()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 5.1158

Importance

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