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

ApplicationConfig   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 136
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 17
c 2
b 0
f 0
lcom 1
cbo 7
dl 0
loc 136
rs 10

12 Methods

Rating   Name   Duplication   Size   Complexity  
B fromFiles() 0 28 2
A __construct() 0 5 1
A getIterator() 0 4 1
A getKeys() 0 4 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 IteratorAggregate;
7
use TomPHP\ConfigServiceProvider\Exception\EntryDoesNotExistException;
8
use TomPHP\ConfigServiceProvider\Exception\NoMatchingFilesException;
9
use TomPHP\ConfigServiceProvider\Exception\ReadOnlyException;
10
11
final class ApplicationConfig implements ArrayAccess, IteratorAggregate
12
{
13
    /**
14
     * @var array
15
     */
16
    private $config;
17
18
    /**
19
     * @var string
20
     */
21
    private $separator;
22
23
    /**
24
     * @api
25
     *
26
     * @param array  $patterns
27
     * @param string $separator
28
     *
29
     * @return ApplicationConfig
30
     */
31
    public static function fromFiles(array $patterns, $separator = '.')
32
    {
33
        $locator = new FileLocator();
34
        $files   = $locator->locate($patterns);
35
36
        if (empty($files)) {
37
            throw new NoMatchingFilesException(
38
                'No files found matching patterns: ' . implode(', ', $patterns)
39
            );
40
        }
41
42
        $factory = new ReaderFactory([
43
            '.json' => 'TomPHP\ConfigServiceProvider\JSONFileReader',
44
            '.php'  => 'TomPHP\ConfigServiceProvider\PHPFileReader',
45
        ]);
46
47
        $configs = array_map(
48
            function ($filename) use ($factory) {
49
                $reader = $factory->create($filename);
50
                return $reader->read($filename);
51
            },
52
            $files
53
        );
54
55
        $config = call_user_func_array('array_replace_recursive', $configs);
56
57
        return new self($config, $separator);
58
    }
59
60
    /**
61
     * @api
62
     *
63
     * @param array  $config
64
     * @param string $separator
65
     */
66
    public function __construct(array $config, $separator = '.')
67
    {
68
        $this->config    = $config;
69
        $this->separator = $separator;
70
    }
71
72
    public function getIterator()
73
    {
74
        return new ApplicationConfigIterator($this);
75
    }
76
77
    /**
78
     * @return array
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use array<integer|string>.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
79
     */
80
    public function getKeys()
81
    {
82
        return array_keys(iterator_to_array(new ApplicationConfigIterator($this)));
83
    }
84
85
    public function offsetExists($offset)
86
    {
87
        try {
88
            $this->traverseConfig($this->getPath($offset));
89
        } catch (EntryDoesNotExistException $e) {
90
            return false;
91
        }
92
93
        return true;
94
    }
95
96
    public function offsetGet($offset)
97
    {
98
        return $this->traverseConfig($this->getPath($offset));
99
    }
100
101
    public function offsetSet($offset, $value)
102
    {
103
        throw new ReadOnlyException('Config is read only.');
104
    }
105
106
    public function offsetUnset($offset)
107
    {
108
        throw new ReadOnlyException('Config is read only.');
109
    }
110
111
    /**
112
     * @return array
113
     */
114
    public function asArray()
115
    {
116
        return $this->config;
117
    }
118
119
    /**
120
     * @return string
121
     */
122
    public function getSeparator()
123
    {
124
        return $this->separator;
125
    }
126
127
    private function getPath($offset)
128
    {
129
        return explode($this->separator, $offset);
130
    }
131
132
    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...
133
    {
134
        $pointer = &$this->config;
135
136
        foreach ($path as $node) {
137
            if (!is_array($pointer) || !array_key_exists($node, $pointer)) {
138
                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...
139
            }
140
141
            $pointer = &$pointer[$node];
142
        }
143
144
        return $pointer;
145
    }
146
}
147