Passed
Pull Request — master (#1676)
by Arnaud
10:22 queued 04:04
created

Config::valid()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 37
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 9.2312

Importance

Changes 6
Bugs 0 Features 0
Metric Value
cc 7
eloc 26
c 6
b 0
f 0
nc 5
nop 0
dl 0
loc 37
ccs 18
cts 28
cp 0.6429
crap 9.2312
rs 8.5706
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\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 1
    public function __construct(?array $config = null)
48
    {
49
        // load default configuration
50 1
        $defaultConfig = realpath(Util::joinFile(__DIR__, '..', 'config/default.php'));
51 1
        if (Plateform::isPhar()) {
52
            $defaultConfig = Util::joinPath(Plateform::getPharPath(), 'config/default.php');
53
        }
54 1
        $this->data = new Data(include $defaultConfig);
55
56
        // import site config
57 1
        $this->siteConfig = $config;
58 1
        $this->importSiteConfig();
59
    }
60
61
    /**
62
     * Imports site configuration.
63
     */
64 1
    private function importSiteConfig(): void
65
    {
66 1
        $this->data->import($this->siteConfig, Data::REPLACE);
67
68
        /**
69
         * Overrides configuration with environment variables.
70
         */
71 1
        $data = $this->getData();
72 1
        $applyEnv = function ($array) use ($data) {
73 1
            $iterator = new \RecursiveIteratorIterator(
74 1
                new \RecursiveArrayIterator($array),
75 1
                \RecursiveIteratorIterator::SELF_FIRST
76 1
            );
77 1
            $iterator->rewind();
78 1
            while ($iterator->valid()) {
79 1
                $path = [];
80 1
                foreach (range(0, $iterator->getDepth()) as $depth) {
81 1
                    $path[] = $iterator->getSubIterator($depth)->key();
82
                }
83 1
                $sPath = implode('_', $path);
84 1
                if ($getEnv = getenv('CECIL_' . strtoupper($sPath))) {
85 1
                    $data->set(str_replace('_', '.', strtolower($sPath)), $this->castSetValue($getEnv));
86
                }
87 1
                $iterator->next();
88
            }
89 1
        };
90 1
        $applyEnv($data->export());
91
    }
92
93
    /**
94
     * Casts boolean value given to set() as string.
95
     *
96
     * @param mixed $value
97
     *
98
     * @return bool|mixed
99
     */
100 1
    private function castSetValue($value)
101
    {
102 1
        if (\is_string($value)) {
103
            switch ($value) {
104 1
                case 'true':
105 1
                    return true;
106 1
                case 'false':
107
                    return false;
108
                default:
109 1
                    return $value;
110
            }
111
        }
112
113
        return $value;
114
    }
115
116
    /**
117
     * Imports (theme) configuration.
118
     */
119 1
    public function import(array $config): void
120
    {
121 1
        $this->data->import($config, Data::REPLACE);
122
123
        // re-import site config
124 1
        $this->importSiteConfig();
125
126
        // checks the configuration
127 1
        $this->valid();
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 1
    public function has(string $key): bool
142
    {
143 1
        return $this->data->has($key);
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 1
    public function get(string $key, ?string $language = null, bool $fallback = true)
156
    {
157 1
        if ($language !== null) {
158 1
            $langIndex = $this->getLanguageIndex($language);
159 1
            $keyLang = "languages.$langIndex.config.$key";
160 1
            if ($this->data->has($keyLang)) {
161 1
                return $this->data->get($keyLang);
162
            }
163 1
            if ($language !== $this->getLanguageDefault() && $fallback === false) {
164 1
                return null;
165
            }
166
        }
167 1
        if ($this->data->has($key)) {
168 1
            return $this->data->get($key);
169
        }
170
171 1
        return null;
172
    }
173
174
    /**
175
     * Set the source directory.
176
     *
177
     * @throws \InvalidArgumentException
178
     */
179 1
    public function setSourceDir(string $sourceDir = null): self
180
    {
181 1
        if ($sourceDir === null) {
182 1
            $sourceDir = getcwd();
183
        }
184 1
        if (!is_dir($sourceDir)) {
185
            throw new \InvalidArgumentException(sprintf('The directory "%s" is not a valid source!', $sourceDir));
186
        }
187 1
        $this->sourceDir = $sourceDir;
188
189 1
        return $this;
190
    }
191
192
    /**
193
     * Get the source directory.
194
     */
195 1
    public function getSourceDir(): string
196
    {
197 1
        return $this->sourceDir;
198
    }
199
200
    /**
201
     * Set the destination directory.
202
     *
203
     * @throws \InvalidArgumentException
204
     */
205 1
    public function setDestinationDir(string $destinationDir = null): self
206
    {
207 1
        if ($destinationDir === null) {
208 1
            $destinationDir = $this->sourceDir;
209
        }
210 1
        if (!is_dir($destinationDir)) {
211
            throw new \InvalidArgumentException(sprintf(
212
                'The directory "%s" is not a valid destination!',
213
                $destinationDir
214
            ));
215
        }
216 1
        $this->destinationDir = $destinationDir;
217
218 1
        return $this;
219
    }
220
221
    /**
222
     * Get the destination directory.
223
     */
224 1
    public function getDestinationDir(): string
225
    {
226 1
        return $this->destinationDir;
227
    }
228
229
    /*
230
     * Path helpers.
231
     */
232
233
    /**
234
     * Returns the path of the pages directory.
235
     */
236 1
    public function getPagesPath(): string
237
    {
238 1
        return Util::joinFile($this->getSourceDir(), (string) $this->get('pages.dir'));
239
    }
240
241
    /**
242
     * Returns the path of the output directory.
243
     */
244 1
    public function getOutputPath(): string
245
    {
246 1
        return Util::joinFile($this->getDestinationDir(), (string) $this->get('output.dir'));
247
    }
248
249
    /**
250
     * Returns the path of the data directory.
251
     */
252 1
    public function getDataPath(): string
253
    {
254 1
        return Util::joinFile($this->getSourceDir(), (string) $this->get('data.dir'));
255
    }
256
257
    /**
258
     * Returns the path of templates directory.
259
     */
260 1
    public function getLayoutsPath(): string
261
    {
262 1
        return Util::joinFile($this->getSourceDir(), (string) $this->get('layouts.dir'));
263
    }
264
265
    /**
266
     * Returns the path of internal templates directory.
267
     */
268 1
    public function getLayoutsInternalPath(): string
269
    {
270 1
        return Util::joinPath(__DIR__, '..', (string) $this->get('layouts.internal.dir'));
271
    }
272
273
    /**
274
     * Returns the path of translations directory.
275
     */
276 1
    public function getTranslationsPath(): string
277
    {
278 1
        return Util::joinFile($this->getSourceDir(), (string) $this->get('layouts.translations.dir'));
279
    }
280
281
    /**
282
     * Returns the path of internal translations directory.
283
     */
284 1
    public function getTranslationsInternalPath(): string
285
    {
286 1
        if (Util\Plateform::isPhar()) {
287
            return Util::joinPath(Plateform::getPharPath(), (string) $this->get('layouts.translations.internal.dir'));
288
        }
289
290 1
        return realpath(Util::joinPath(__DIR__, '..', (string) $this->get('layouts.translations.internal.dir')));
291
    }
292
293
    /**
294
     * Returns the path of themes directory.
295
     */
296 1
    public function getThemesPath(): string
297
    {
298 1
        return Util::joinFile($this->getSourceDir(), (string) $this->get('themes.dir'));
299
    }
300
301
    /**
302
     * Returns the path of static files directory.
303
     */
304 1
    public function getStaticPath(): string
305
    {
306 1
        return Util::joinFile($this->getSourceDir(), (string) $this->get('static.dir'));
307
    }
308
309
    /**
310
     * Returns the path of static files directory, with a target.
311
     */
312 1
    public function getStaticTargetPath(): string
313
    {
314 1
        $path = $this->getStaticPath();
315
316 1
        if (!empty($this->get('static.target'))) {
317
            $path = substr($path, 0, -\strlen((string) $this->get('static.target')));
318
        }
319
320 1
        return $path;
321
    }
322
323
    /**
324
     * Returns the path of assets files directory.
325
     */
326 1
    public function getAssetsPath(): string
327
    {
328 1
        return Util::joinFile($this->getSourceDir(), (string) $this->get('assets.dir'));
329
    }
330
331
    /**
332
     * Returns cache path.
333
     *
334
     * @throws RuntimeException
335
     */
336 1
    public function getCachePath(): string
337
    {
338 1
        if (empty((string) $this->get('cache.dir'))) {
339
            throw new RuntimeException(sprintf('The cache directory ("%s") is not defined in configuration.', '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(), (string) $this->get('cache.templates.dir'));
358
    }
359
360
    /**
361
     * Returns cache path of translations.
362
     */
363 1
    public function getCacheTranslationsPath(): string
364
    {
365 1
        return Util::joinFile($this->getCachePath(), (string) $this->get('cache.translations.dir'));
366
    }
367
368
    /**
369
     * Returns cache path of assets.
370
     */
371 1
    public function getCacheAssetsPath(): string
372
    {
373 1
        return Util::joinFile($this->getCachePath(), (string) $this->get('cache.assets.dir'));
374
    }
375
376
    /**
377
     * Returns cache path of remote assets.
378
     */
379 1
    public function getCacheAssetsRemotePath(): string
380
    {
381 1
        return Util::joinFile($this->getCacheAssetsPath(), (string) $this->get('cache.assets.remote.dir'));
382
    }
383
384
    /*
385
     * Output helpers.
386
     */
387
388
    /**
389
     * Returns the property value of an output format.
390
     *
391
     * @throws RuntimeException
392
     *
393
     * @return string|array|null
394
     */
395 1
    public function getOutputFormatProperty(string $name, string $property)
396
    {
397 1
        $properties = array_column((array) $this->get('output.formats'), $property, 'name');
398
399 1
        if (empty($properties)) {
400
            throw new RuntimeException(sprintf('Property "%s" is not defined for format "%s".', $property, $name));
401
        }
402
403 1
        return $properties[$name] ?? null;
404
    }
405
406
    /*
407
     * Assets helpers.
408
     */
409
410
    /**
411
     * Returns asset image widths.
412
     */
413 1
    public function getAssetsImagesWidths(): array
414
    {
415 1
        return \count((array) $this->get('assets.images.responsive.widths')) > 0 ? (array) $this->get('assets.images.responsive.widths') : [480, 640, 768, 1024, 1366, 1600, 1920];
416
    }
417
418
    /**
419
     * Returns asset image sizes.
420
     */
421 1
    public function getAssetsImagesSizes(): array
422
    {
423 1
        return \count((array) $this->get('assets.images.responsive.sizes')) > 0 ? (array) $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 RuntimeException
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 RuntimeException(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 RuntimeException
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 RuntimeException(sprintf('The default language "%s" is not listed in "languages" key configuration.', $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 RuntimeException
507
     */
508 1
    public function getLanguageDefault(): string
509
    {
510 1
        if (!$this->get('language')) {
511
            throw new RuntimeException('There is no default "language" key in configuration.');
512
        }
513
514 1
        if ($this->get('language.code')) {
515
            return $this->get('language.code');
516
        }
517
518 1
        return $this->get('language');
519
    }
520
521
    /**
522
     * Returns a language code index.
523
     *
524
     * @throws RuntimeException
525
     */
526 1
    public function getLanguageIndex(string $code): int
527
    {
528 1
        $array = array_column($this->getLanguages(), 'code');
529
530 1
        if (false === $index = array_search($code, $array)) {
531
            throw new RuntimeException(sprintf('The language code "%s" is not defined.', $code));
532
        }
533
534 1
        return $index;
535
    }
536
537
    /**
538
     * Returns the property value of a (specified or the default) language.
539
     *
540
     * @throws RuntimeException
541
     */
542 1
    public function getLanguageProperty(string $property, ?string $code = null): string
543
    {
544 1
        $code = $code ?? $this->getLanguageDefault();
545
546 1
        $properties = array_column($this->getLanguages(), $property, 'code');
547
548 1
        if (empty($properties)) {
549
            throw new RuntimeException(sprintf('Property "%s" is not defined for language "%s".', $property, $code));
550
        }
551
552 1
        return $properties[$code];
553
    }
554
555
    /*
556
     * Cache helpers.
557
     */
558
559
    /**
560
     * Is cache dir is absolute to system files
561
     * or relative to project destination?
562
     */
563 1
    public function isCacheDirIsAbsolute(): bool
564
    {
565 1
        $path = (string) $this->get('cache.dir');
566 1
        if (Util::joinFile($path) == realpath(Util::joinFile($path))) {
567
            return true;
568
        }
569
570 1
        return false;
571
    }
572
573
    /**
574
     * Set a Data object as configuration.
575
     */
576
    protected function setData(Data $data): self
577
    {
578
        if ($this->data !== $data) {
579
            $this->data = $data;
580
        }
581
582
        return $this;
583
    }
584
585
    /**
586
     * Get configuration as a Data object.
587
     */
588 1
    protected function getData(): Data
589
    {
590 1
        return $this->data;
591
    }
592
593
    /**
594
     * Valid the configuration.
595
     */
596 1
    private function valid(): void
597
    {
598
        // default language must be valid
599 1
        if (!preg_match('/^' . Config::LANG_CODE_PATTERN . '$/', (string) $this->get('language'))) {
600
            throw new ConfigException(sprintf('Default language code "%s" is not valid (e.g.: "language: fr-FR").', $this->get('language')));
601
        }
602
        // if language is set then the locale is required
603 1
        foreach ((array) $this->get('languages') as $lang) {
604 1
            if (!isset($lang['locale'])) {
605
                throw new ConfigException('A language locale is not defined.');
606
            }
607 1
            if (!preg_match('/^' . Config::LANG_LOCALE_PATTERN . '$/', $lang['locale'])) {
608
                throw new ConfigException(sprintf('The language locale "%s" is not valid (e.g.: "locale: fr_FR").', $lang['locale']));
609
            }
610
        }
611
        // Version 8.x breaking changes
612 1
        $toV8 = [
613 1
            'frontmatter'  => 'pages:frontmatter',
614 1
            'body'         => 'pages:body',
615 1
            'defaultpages' => 'pages:default',
616 1
            'virtualpages' => 'pages:virtual',
617 1
            'generators'   => 'pages:generators',
618 1
            'paths'        => 'pages:paths',
619 1
            'translations' => 'layouts:translations',
620 1
            'extensions'   => 'layouts:extensions',
621 1
            'postprocess'  => 'optimize',
622 1
        ];
623 1
        array_walk($toV8, function ($to, $from) {
624 1
            if ($this->has($from)) {
625
                $path = explode(':', $to);
626
                $step = 0;
627
                $formatedPath = '';
628
                foreach ($path as $fragment) {
629
                    $step = $step + 2;
630
                    $formatedPath .= "$fragment:\n" . str_pad(' ', $step);
631
                }
632
                throw new ConfigException("Option `$from:` must be moved to:\n```\n$formatedPath\n```");
633
            }
634 1
        });
635
    }
636
}
637