Passed
Push — feat/content_to_pages ( 41bab6 )
by Arnaud
03:44
created

Config::getLayoutsPath()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
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\RuntimeException;
17
use Cecil\Util\Plateform;
18
use Dflydev\DotAccessData\Data;
19
20
/**
21
 * Class Config.
22
 */
23
class Config
24
{
25
    /** @var Data Configuration is a Data object. */
26
    protected $data;
27
28
    /** @var array Configuration. */
29
    protected $siteConfig;
30
31
    /** @var string Source directory. */
32
    protected $sourceDir;
33
34
    /** @var string Destination directory. */
35
    protected $destinationDir;
36
37
    /** @var array Languages. */
38
    protected $languages = null;
39
40
    /**
41
     * @param array|null $config
42
     */
43
    public function __construct(array $config = null)
44
    {
45
        // load default configuration
46
        $defaultConfig = realpath(Util::joinFile(__DIR__, '..', 'config/default.php'));
47
        if (Plateform::isPhar()) {
48
            $defaultConfig = Util::joinPath(Plateform::getPharPath(), 'config/default.php');
49
        }
50
        $this->data = new Data(include $defaultConfig);
51
52
        // import site config
53
        $this->siteConfig = $config;
54
        $this->importSiteConfig();
55
    }
56
57
    /**
58
     * Imports site configuration.
59
     */
60
    protected function importSiteConfig(): void
61
    {
62
        $this->data->import($this->siteConfig);
63
64
        /**
65
         * Overrides configuration with environment variables.
66
         */
67
        $data = $this->getData();
68
        $applyEnv = function ($array) use ($data) {
69
            $iterator = new \RecursiveIteratorIterator(
70
                new \RecursiveArrayIterator($array),
71
                \RecursiveIteratorIterator::SELF_FIRST
72
            );
73
            $iterator->rewind();
74
            while ($iterator->valid()) {
75
                $path = [];
76
                foreach (range(0, $iterator->getDepth()) as $depth) {
77
                    $path[] = $iterator->getSubIterator($depth)->key();
78
                }
79
                $sPath = implode('_', $path);
80
                if ($getEnv = getenv('CECIL_'.strtoupper($sPath))) {
81
                    $data->set(str_replace('_', '.', strtolower($sPath)), $this->castSetValue($getEnv));
82
                }
83
                $iterator->next();
84
            }
85
        };
86
        $applyEnv($data->export());
87
    }
88
89
    /**
90
     * Casts boolean value given to set() as string.
91
     */
92
    private function castSetValue($value)
93
    {
94
        if (is_string($value)) {
95
            switch ($value) {
96
                case 'true':
97
                    return true;
98
                case 'false':
99
                    return false;
100
                default:
101
                    return $value;
102
            }
103
        }
104
105
        return $value;
106
    }
107
108
    /**
109
     * Imports (theme) configuration.
110
     *
111
     * @param array|null $config
112
     */
113
    public function import(array $config): void
114
    {
115
        $this->data->import($config);
116
117
        // re-import site config
118
        $this->importSiteConfig();
119
    }
120
121
    /**
122
     * Set a Data object as configuration.
123
     */
124
    protected function setData(Data $data): self
125
    {
126
        if ($this->data !== $data) {
127
            $this->data = $data;
128
        }
129
130
        return $this;
131
    }
132
133
    /**
134
     * Get configuration as a Data object.
135
     */
136
    public function getData(): Data
137
    {
138
        return $this->data;
139
    }
140
141
    /**
142
     * Get configuration as an array.
143
     */
144
    public function getAsArray(): array
145
    {
146
        return $this->data->export();
147
    }
148
149
    /**
150
     * Is configuration's key exists?
151
     */
152
    public function has(string $key): bool
153
    {
154
        return $this->data->has($key);
155
    }
156
157
    /**
158
     * Get the value of a configuration's key.
159
     *
160
     * @return mixed|null
161
     */
162
    public function get(string $key, string $language = null, bool $fallback = true)
163
    {
164
        if ($language !== null) {
165
            $index = $this->getLanguageIndex($language);
166
            $keyLang = \sprintf('languages.%s.config.%s', $index, $key);
167
            if ($this->data->has($keyLang)) {
168
                return $this->data->get($keyLang);
169
            }
170
            if ($language !== $this->getLanguageDefault() && $fallback === false) {
171
                return null;
172
            }
173
        }
174
175
        if ($this->data->has($key)) {
176
            return $this->data->get($key);
177
        }
178
179
        return null;
180
    }
181
182
    /**
183
     * Set the source directory.
184
     *
185
     * @throws \InvalidArgumentException
186
     */
187
    public function setSourceDir(string $sourceDir = null): self
188
    {
189
        if ($sourceDir === null) {
190
            $sourceDir = getcwd();
191
        }
192
        if (!is_dir($sourceDir)) {
193
            throw new \InvalidArgumentException(\sprintf('The directory "%s" is not a valid source!', $sourceDir));
194
        }
195
        $this->sourceDir = $sourceDir;
196
197
        return $this;
198
    }
199
200
    /**
201
     * Get the source directory.
202
     */
203
    public function getSourceDir(): string
204
    {
205
        return $this->sourceDir;
206
    }
207
208
    /**
209
     * Set the destination directory.
210
     *
211
     * @throws \InvalidArgumentException
212
     */
213
    public function setDestinationDir(string $destinationDir = null): self
214
    {
215
        if ($destinationDir === null) {
216
            $destinationDir = $this->sourceDir;
217
        }
218
        if (!is_dir($destinationDir)) {
219
            throw new \InvalidArgumentException(\sprintf(
220
                'The directory "%s" is not a valid destination!',
221
                $destinationDir
222
            ));
223
        }
224
        $this->destinationDir = $destinationDir;
225
226
        return $this;
227
    }
228
229
    /**
230
     * Get the destination directory.
231
     */
232
    public function getDestinationDir(): string
233
    {
234
        return $this->destinationDir;
235
    }
236
237
    /**
238
     * Path helpers.
239
     */
240
241
    /**
242
     * Returns the path of the pages directory.
243
     */
244
    public function getPagesPath(): string
245
    {
246
        $path = Util::joinFile($this->getSourceDir(), (string) $this->get('pages.dir'));
247
248
        // legacy support
249
        if (!is_dir($path)) {
250
            $path = Util::joinFile($this->getSourceDir(), 'content');
251
        }
252
253
        return $path;
254
    }
255
256
    /**
257
     * Returns the path of the data directory.
258
     */
259
    public function getDataPath(): string
260
    {
261
        return Util::joinFile($this->getSourceDir(), (string) $this->get('data.dir'));
262
    }
263
264
    /**
265
     * Returns the path of templates directory.
266
     */
267
    public function getLayoutsPath(): string
268
    {
269
        return Util::joinFile($this->getSourceDir(), (string) $this->get('layouts.dir'));
270
    }
271
272
    /**
273
     * Returns the path of themes directory.
274
     */
275
    public function getThemesPath(): string
276
    {
277
        return Util::joinFile($this->getSourceDir(), (string) $this->get('themes.dir'));
278
    }
279
280
    /**
281
     * Returns the path of internal templates directory.
282
     */
283
    public function getInternalLayoutsPath(): string
284
    {
285
        return Util::joinPath(__DIR__, '..', (string) $this->get('layouts.internal.dir'));
286
    }
287
288
    /**
289
     * Returns the path of the output directory.
290
     */
291
    public function getOutputPath(): string
292
    {
293
        return Util::joinFile($this->getDestinationDir(), (string) $this->get('output.dir'));
294
    }
295
296
    /**
297
     * Returns the path of static files directory.
298
     */
299
    public function getStaticPath(): string
300
    {
301
        return Util::joinFile($this->getSourceDir(), (string) $this->get('static.dir'));
302
    }
303
304
    /**
305
     * Returns the path of static files directory, with a target.
306
     */
307
    public function getStaticTargetPath(): string
308
    {
309
        $path = $this->getStaticPath();
310
311
        if (!empty($this->get('static.target'))) {
312
            $path = substr($path, 0, -strlen((string) $this->get('static.target')));
313
        }
314
315
        return $path;
316
    }
317
318
    /**
319
     * Returns the path of assets files directory.
320
     */
321
    public function getAssetsPath(): string
322
    {
323
        return Util::joinFile($this->getSourceDir(), (string) $this->get('assets.dir'));
324
    }
325
326
    /**
327
     * Is cache dir is absolute to system files
328
     * or relative to project destination?
329
     */
330
    public function isCacheDirIsAbsolute(): bool
331
    {
332
        $path = (string) $this->get('cache.dir');
333
        if (Util::joinFile($path) == realpath(Util::joinFile($path))) {
334
            return true;
335
        }
336
337
        return false;
338
    }
339
340
    /**
341
     * Returns cache path.
342
     *
343
     * @throws RuntimeException
344
     */
345
    public function getCachePath(): string
346
    {
347
        if (empty((string) $this->get('cache.dir'))) {
348
            throw new RuntimeException(\sprintf('The cache directory ("%s") is not defined in configuration.', 'cache.dir'));
349
        }
350
351
        if ($this->isCacheDirIsAbsolute()) {
352
            $cacheDir = Util::joinFile((string) $this->get('cache.dir'), 'cecil');
353
            Util\File::getFS()->mkdir($cacheDir);
354
355
            return $cacheDir;
356
        }
357
358
        return Util::joinFile($this->getDestinationDir(), (string) $this->get('cache.dir'));
359
    }
360
361
    /**
362
     * Returns cache path of remote assets.
363
     */
364
    public function getCacheAssetsPath(): string
365
    {
366
        return Util::joinFile($this->getCachePath(), (string) $this->get('cache.assets.dir'));
367
    }
368
369
    /**
370
     * Returns the property value of an output format.
371
     *
372
     * @throws RuntimeException
373
     *
374
     * @return string|array|null
375
     */
376
    public function getOutputFormatProperty(string $name, string $property)
377
    {
378
        $properties = array_column((array) $this->get('output.formats'), $property, 'name');
379
380
        if (empty($properties)) {
381
            throw new RuntimeException(\sprintf('Property "%s" is not defined for format "%s".', $property, $name));
382
        }
383
384
        return $properties[$name] ?? null;
385
    }
386
387
    /**
388
     * Theme helpers.
389
     */
390
391
    /**
392
     * Returns theme(s) as an array.
393
     */
394
    public function getTheme(): ?array
395
    {
396
        if ($themes = $this->get('theme')) {
397
            if (is_array($themes)) {
398
                return $themes;
399
            }
400
401
            return [$themes];
402
        }
403
404
        return null;
405
    }
406
407
    /**
408
     * Has a (valid) theme(s)?
409
     *
410
     * @throws RuntimeException
411
     */
412
    public function hasTheme(): bool
413
    {
414
        if ($themes = $this->getTheme()) {
415
            foreach ($themes as $theme) {
416
                if (!Util\File::getFS()->exists($this->getThemeDirPath($theme, 'layouts'))) {
417
                    throw new RuntimeException(\sprintf('Theme directory "%s" not found!', Util::joinFile($this->getThemesPath(), $theme, 'layouts')));
418
                }
419
            }
420
421
            return true;
422
        }
423
424
        return false;
425
    }
426
427
    /**
428
     * Returns the path of a specific theme's directory.
429
     * ("layouts" by default).
430
     */
431
    public function getThemeDirPath(string $theme, string $dir = 'layouts'): string
432
    {
433
        return Util::joinFile($this->getThemesPath(), $theme, $dir);
434
    }
435
436
    /**
437
     * Language helpers.
438
     */
439
440
    /**
441
     * Returns an array of available languages.
442
     *
443
     * @throws RuntimeException
444
     */
445
    public function getLanguages(): array
446
    {
447
        if ($this->languages !== null) {
448
            return $this->languages;
449
        }
450
451
        $languages = (array) $this->get('languages');
452
453
        if (!is_int(array_search($this->getLanguageDefault(), array_column($languages, 'code')))) {
454
            throw new RuntimeException(\sprintf('The default language "%s" is not listed in "languages" key configuration.', $this->getLanguageDefault()));
455
        }
456
457
        $languages = array_filter($languages, function ($language) {
458
            return !(isset($language['enabled']) && $language['enabled'] === false);
459
        });
460
461
        $this->languages = $languages;
462
463
        return $this->languages;
464
    }
465
466
    /**
467
     * Returns the default language code (ie: "en", "fr-fr", etc.).
468
     *
469
     * @throws RuntimeException
470
     */
471
    public function getLanguageDefault(): string
472
    {
473
        if (!$this->get('language')) {
474
            throw new RuntimeException('There is no default "language" key in configuration.');
475
        }
476
477
        return $this->get('language');
478
    }
479
480
    /**
481
     * Returns a language code index.
482
     *
483
     * @throws RuntimeException
484
     */
485
    public function getLanguageIndex(string $code): int
486
    {
487
        $array = array_column($this->getLanguages(), 'code');
488
489
        if (false === $index = array_search($code, $array)) {
490
            throw new RuntimeException(\sprintf('The language code "%s" is not defined.', $code));
491
        }
492
493
        return $index;
494
    }
495
496
    /**
497
     * Returns the property value of a (specified or default) language.
498
     *
499
     * @throws RuntimeException
500
     */
501
    public function getLanguageProperty(string $property, string $code = null): ?string
502
    {
503
        $code = $code ?? $this->getLanguageDefault();
504
505
        $properties = array_column($this->getLanguages(), $property, 'code');
506
507
        if (empty($properties)) {
508
            throw new RuntimeException(\sprintf('Property "%s" is not defined for language "%s".', $property, $code));
509
        }
510
511
        return $properties[$code];
512
    }
513
}
514