Passed
Pull Request — master (#342)
by Théo
02:37
created

ConfigurationLoader::getConfig()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 31
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 16
dl 0
loc 31
rs 9.7333
c 0
b 0
f 0
cc 4
nc 8
nop 4
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the box project.
7
 *
8
 * (c) Kevin Herrera <[email protected]>
9
 *     Théo Fidry <[email protected]>
10
 *
11
 * This source file is subject to the MIT license that is bundled
12
 * with this source code in the file LICENSE.
13
 */
14
15
namespace KevinGH\Box\Console;
16
17
use InvalidArgumentException;
18
use KevinGH\Box\Configuration;
19
use KevinGH\Box\Json\JsonValidationException;
20
use KevinGH\Box\NoConfigurationFound;
21
use Symfony\Component\Console\Style\SymfonyStyle;
22
use function sprintf;
23
24
/**
25
 * @private
26
 */
27
final class ConfigurationLoader
28
{
29
    /**
30
     * Returns the configuration settings.
31
     *
32
     * @param bool $allowNoFile Load the config nonetheless if not file is found when true
33
     *
34
     * @throws JsonValidationException
35
     */
36
    public static function getConfig(
37
        ?string $configPath,
38
        ConfigurationHelper $helper,
39
        SymfonyStyle $io,
40
        bool $allowNoFile
41
    ): Configuration {
42
        try {
43
            $configPath = $configPath ?? $helper->findDefaultPath();
44
45
            $io->comment(
46
                sprintf(
47
                    'Loading the configuration file "<comment>%s</comment>".',
48
                    $configPath
49
                )
50
            );
51
        } catch (NoConfigurationFound $exception) {
52
            if (false === $allowNoFile) {
53
                throw $exception;
54
            }
55
56
            $io->comment('Loading without a configuration file.');
57
58
            $configPath = null;
59
        }
60
61
        try {
62
            return $helper->loadFile($configPath);
63
        } catch (InvalidArgumentException $exception) {
64
            $io->error('The configuration file is invalid.');
65
66
            throw $exception;
67
        }
68
    }
69
}
70