ConfigReader::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 2
nc 1
nop 1
crap 2
1
<?php
2
/**
3
 * Sandro Keil (https://sandro-keil.de)
4
 *
5
 * @link      http://github.com/sandrokeil/interop-config for the canonical source repository
6
 * @copyright Copyright (c) 2017-2020 Sandro Keil
7
 * @license   http://github.com/sandrokeil/interop-config/blob/master/LICENSE.md New BSD License
8
 */
9
10
namespace Interop\Config\Tool;
11
12
use Interop\Config\Exception\OptionNotFoundException;
13
use Interop\Config\RequiresConfig;
14
use Interop\Config\RequiresConfigId;
15
16
class ConfigReader extends AbstractConfig
17
{
18
    const CONFIG_TEMPLATE = '%s;';
19
20
    /**
21
     * @var ConsoleHelper
22
     */
23
    private $helper;
24
25 4
    public function __construct(ConsoleHelper $helper = null)
26
    {
27 4
        $this->helper = $helper ?: new ConsoleHelper();
28 4
    }
29
30 4
    public function readConfig(array $config, string $className): array
31
    {
32 4
        $reflectionClass = new \ReflectionClass($className);
33
34 4
        $interfaces = $reflectionClass->getInterfaceNames();
35
36 4
        $factory = $reflectionClass->newInstanceWithoutConstructor();
37 4
        $dimensions = [];
38
39 4
        if (in_array(RequiresConfig::class, $interfaces, true)) {
40 4
            $dimensions = $factory->dimensions();
41
        }
42
43 4
        foreach ($dimensions as $dimension) {
44 4
            if (!isset($config[$dimension])) {
45 1
                throw OptionNotFoundException::missingOptions($factory, $dimension, null);
46
            }
47 3
            $config = $config[$dimension];
48
        }
49
50 3
        if (in_array(RequiresConfigId::class, $interfaces, true)) {
51 2
            while (true) {
52 2
                $configId = $this->helper->readLine(implode(', ', array_keys($config)), 'For which config id');
53
54 2
                if ('' !== $configId) {
55 1
                    if (isset($config[$configId])) {
56 1
                        return $config[$configId];
57
                    }
58 1
                    $this->helper->writeErrorMessage(sprintf('No config id with name "%s" exists.', $configId));
59 1
                    continue;
60
                }
61 1
                break;
62
            }
63
        }
64
65 2
        return $config;
66
    }
67
68
    public function dumpConfigFile(iterable $config): string
69
    {
70
        return $this->prepareConfig($config);
71
    }
72
}
73