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

ApplicationConfig::fromFiles()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 28
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 28
rs 8.8571
cc 2
eloc 16
nc 2
nop 2
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 ApplicationConfig 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 ApplicationConfig
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
    /**
72
     * @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...
73
     */
74
    public function getKeys()
75
    {
76
        return array_keys(iterator_to_array(new ApplicationConfigIterator($this)));
77
    }
78
79
    public function offsetExists($offset)
80
    {
81
        try {
82
            $this->traverseConfig($this->getPath($offset));
83
        } catch (EntryDoesNotExistException $e) {
84
            return false;
85
        }
86
87
        return true;
88
    }
89
90
    public function offsetGet($offset)
91
    {
92
        return $this->traverseConfig($this->getPath($offset));
93
    }
94
95
    public function offsetSet($offset, $value)
96
    {
97
        throw new ReadOnlyException('Config is read only.');
98
    }
99
100
    public function offsetUnset($offset)
101
    {
102
        throw new ReadOnlyException('Config is read only.');
103
    }
104
105
    /**
106
     * @return array
107
     */
108
    public function asArray()
109
    {
110
        return $this->config;
111
    }
112
113
    /**
114
     * @return string
115
     */
116
    public function getSeparator()
117
    {
118
        return $this->separator;
119
    }
120
121
    private function getPath($offset)
122
    {
123
        return explode($this->separator, $offset);
124
    }
125
126
    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...
127
    {
128
        $pointer = &$this->config;
129
130
        foreach ($path as $node) {
131
            if (!is_array($pointer) || !array_key_exists($node, $pointer)) {
132
                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...
133
            }
134
135
            $pointer = &$pointer[$node];
136
        }
137
138
        return $pointer;
139
    }
140
}
141