Completed
Push — master ( 83bd2d...9517e2 )
by Arne
03:10
created

ConfigurationFileReader::getConfiguration()   C

Complexity

Conditions 10
Paths 14

Size

Total Lines 52
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 52
rs 6.2553
c 0
b 0
f 0
cc 10
eloc 25
nc 14
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Archivr;
4
5
use Archivr\Exception\ConfigurationException;
6
use Zend\Stdlib\ArrayUtils;
7
8
class ConfigurationFileReader
9
{
10
    public function getConfiguration(string $configurationFilePath)
11
    {
12
        $json = file_get_contents($configurationFilePath);
13
14
        if (!$json)
15
        {
16
            throw new \RuntimeException(sprintf('Configuration file path "%s" does not exist or is not readable.', $configurationFilePath));
17
        }
18
19
        $array = json_decode($json, true);
20
        $array = ArrayUtils::merge([
21
            'path' => dirname($configurationFilePath)
22
        ], $array);
23
24
        foreach (['path', 'vaults'] as $requiredKey)
25
        {
26
            if (!array_key_exists($requiredKey, $array))
27
            {
28
                throw new ConfigurationException(sprintf('Missing config key: %s.', $requiredKey));
29
            }
30
        }
31
32
        if (!is_array($array['vaults']))
33
        {
34
            throw new ConfigurationException(sprintf('Configuration key \'vaults\' has to be an array.'));
35
        }
36
37
        if (empty($array['vaults']))
38
        {
39
            throw new ConfigurationException(sprintf('At least one vault configuration has to be present.'));
40
        }
41
42
        $configuration = new Configuration();
43
        $configuration->setLocalPath($array['path']);
44
45
        foreach ($array['vaults'] as $index => $vaultConfig)
46
        {
47
            if (empty($vaultConfig['adapter']))
48
            {
49
                throw new ConfigurationException(sprintf('Vault configuration #%d is missing the obligatory \'adapter\' key.', $index));
50
            }
51
52
            $lockAdapter = empty($vaultConfig['lockAdapter']) ? 'connection' : $vaultConfig['lockAdapter'];
53
54
            $connectionConfig = new ConnectionConfiguration($vaultConfig['adapter'], $lockAdapter);
55
            $connectionConfig->setSettings($vaultConfig['settings'] ?: []);
56
57
            $configuration->addConnectionConfiguration($connectionConfig);
58
        }
59
60
        return $configuration;
61
    }
62
}
63