Completed
Pull Request — master (#28)
by Tom
02:28
created

Config   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 123
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 3
Bugs 0 Features 3
Metric Value
wmc 15
c 3
b 0
f 3
lcom 1
cbo 6
dl 0
loc 123
rs 10

10 Methods

Rating   Name   Duplication   Size   Complexity  
B fromFiles() 0 28 2
A __construct() 0 5 1
A offsetExists() 0 10 2
A offsetGet() 0 4 1
A offsetSet() 0 4 1
A offsetUnset() 0 4 1
A asArray() 0 4 1
A getSeparator() 0 4 1
A getPath() 0 4 1
A traverseConfig() 0 14 4
1
<?php
2
3
namespace TomPHP\ConfigServiceProvider;
4
5
use ArrayAccess;
6
use TomPHP\ConfigServiceProvider\Exception\EntryDoesNotExistException;
7
use TomPHP\ConfigServiceProvider\Exception\NoMatchingFilesException;
8
use TomPHP\ConfigServiceProvider\Exception\ReadOnlyException;
9
10
final class Config implements ArrayAccess
11
{
12
    /**
13
     * @var array
14
     */
15
    private $config;
16
17
    /**
18
     * @var string
19
     */
20
    private $separator;
21
22
    /**
23
     * @api
24
     *
25
     * @param array  $patterns
26
     * @param string $separator
27
     *
28
     * @return self
29
     */
30
    public static function fromFiles(array $patterns, $separator = '.')
31
    {
32
        $locator = new FileLocator();
33
        $files   = $locator->locate($patterns);
34
35
        if (empty($files)) {
36
            throw new NoMatchingFilesException(
37
                'No files found matching patterns: ' . implode(', ', $patterns)
38
            );
39
        }
40
41
        $factory = new ReaderFactory([
42
            '.json' => 'TomPHP\ConfigServiceProvider\JSONFileReader',
43
            '.php'  => 'TomPHP\ConfigServiceProvider\PHPFileReader',
44
        ]);
45
46
        $configs = array_map(
47
            function ($filename) use ($factory) {
48
                $reader = $factory->create($filename);
49
                return $reader->read($filename);
50
            },
51
            $files
52
        );
53
54
        $config = call_user_func_array('array_replace_recursive', $configs);
55
56
        return new self($config, $separator);
57
    }
58
59
    /**
60
     * @api
61
     *
62
     * @param array  $config
63
     * @param string $separator
64
     */
65
    public function __construct(array $config, $separator = '.')
66
    {
67
        $this->config    = $config;
68
        $this->separator = $separator;
69
    }
70
71
    public function offsetExists($offset)
72
    {
73
        try {
74
            $this->traverseConfig($this->getPath($offset));
75
        } catch (EntryDoesNotExistException $e) {
76
            return false;
77
        }
78
79
        return true;
80
    }
81
82
    public function offsetGet($offset)
83
    {
84
        return $this->traverseConfig($this->getPath($offset));
85
    }
86
87
    public function offsetSet($offset, $value)
88
    {
89
        throw new ReadOnlyException('Config is read only.');
90
    }
91
92
    public function offsetUnset($offset)
93
    {
94
        throw new ReadOnlyException('Config is read only.');
95
    }
96
97
    /**
98
     * @return array
99
     */
100
    public function asArray()
101
    {
102
        return $this->config;
103
    }
104
105
    /**
106
     * @return string
107
     */
108
    public function getSeparator()
109
    {
110
        return $this->separator;
111
    }
112
113
    private function getPath($offset)
114
    {
115
        return explode($this->separator, $offset);
116
    }
117
118
    private function traverseConfig(array $path)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
119
    {
120
        $pointer = &$this->config;
121
122
        foreach ($path as $node) {
123
            if (!is_array($pointer) || !array_key_exists($node, $pointer)) {
124
                throw new EntryDoesNotExistException("No entry found for " . implode($this->separator, $path));
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal No entry found for does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
125
            }
126
127
            $pointer = &$pointer[$node];
128
        }
129
130
        return $pointer;
131
    }
132
}
133