Xml::__construct()   C
last analyzed

Complexity

Conditions 9
Paths 15

Size

Total Lines 49
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 49
rs 5.7446
c 0
b 0
f 0
cc 9
eloc 30
nc 15
nop 2
1
<?php
2
declare(strict_types = 1);
3
4
/**
5
 * Micro
6
 *
7
 * @author    Raffael Sahli <[email protected]>
8
 * @copyright Copyright (c) 2017 gyselroth GmbH (https://gyselroth.com)
9
 * @license   MIT https://opensource.org/licenses/MIT
10
 */
11
12
namespace Micro\Config;
13
14
use \Micro\Config;
15
use \SimpleXMLElement;
16
17
class Xml implements ConfigInterface
18
{
19
    /**
20
     * Config features namespace
21
     */
22
    const CONFIG_FEATURE_NAMESPACE = 'https://github.com/gyselroth/micro';
23
24
    /**
25
     * Config features namespace prefix
26
     */
27
    const CONFIG_FEATURE_NAMESPACE_PREFIX = 'm';
28
29
30
    /**
31
     * Store
32
     *
33
     * @var SimpleXML
34
     */
35
    private $store;
36
37
38
    /**
39
     * Load config
40
     *
41
     * @param   string $config
42
     * @param   string $env
43
     * @return  void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
44
     */
45
    public function __construct(string $config, string $env = 'production')
46
    {
47
        $config = simplexml_load_file($config);
48
        if ($this->store === false) {
49
            throw new Exception('failed load xml configuration');
50
        }
51
52
        $store = (array)$config->children();
53
        if (!isset($store[$env])) {
54
            throw new Exception('env '.$env.' is not configured');
55
        }
56
57
        $config = $store[$env];
58
59
        foreach ($store as $reg) {
60
            $result = $reg->xpath('/config/'.$reg->getName().'//*[@'.self::CONFIG_FEATURE_NAMESPACE_PREFIX.':inherits]');
61
            while (list(, $node) = each($result)) {
62
                $path = (string)$node->attributes(self::CONFIG_FEATURE_NAMESPACE)->inherits;
63
64
                if ($path === '') {
65
                    continue;
66
                }
67
68
                $xpath = '/config/'.$reg->getName().'/'.str_replace('.', '/', $path).'';
69
                $found = $reg->xpath($xpath);
70
                if (count($found) !== 1) {
71
                    throw new Exception('inherits '.$xpath.' not found');
72
                }
73
74
                unset($node->attributes(self::CONFIG_FEATURE_NAMESPACE)->inherits);
75
                $found = array_shift($found);
76
77
                $temp = clone $found;
78
                $this->appendSimplexml($temp, $node);
79
                $this->appendSimplexml($node, $temp);
80
            }
81
        }
82
83
        $attrs = $store[$env]->attributes(self::CONFIG_FEATURE_NAMESPACE);
84
        if (isset($attrs['inherits'])) {
85
            if (!isset($store[(string)$attrs['inherits']])) {
86
                throw new Exception('parent env '.$attrs['inherits'].' is not configured');
87
            } else {
88
                $this->appendSimplexml($store[(string)$attrs['inherits']], $config);
89
            }
90
        }
91
92
        $this->store = $config;
93
    }
94
95
96
    /**
97
     * Merge xml tree's
98
     *
99
     * @param   SimpleXMLElement $simplexml_to
100
     * @param   SimpleXMLElement $simplexml_from
101
     * @return  bool
102
     */
103
    protected function appendSimplexml(SimpleXMLElement&$simplexml_to, SimpleXMLElement&$simplexml_from): bool
104
    {
105
        if (count($simplexml_from->children()) === 0) {
106
            if (count($simplexml_to->children()) === 0) {
107
                $simplexml_to[0] = htmlspecialchars((string)$simplexml_from);
108
            }
109
        }
110
        $attrs = $simplexml_to->attributes();
111
        foreach ($simplexml_from->attributes() as $attr_key => $attr_value) {
112
            if (!isset($attrs[$attr_key])) {
113
                $simplexml_to->addAttribute($attr_key, (string)$attr_value);
114
            } else {
115
                $simplexml_to->attributes()->{$attr_key} = (string)$attr_value;
116
            }
117
        }
118
        foreach ($simplexml_from->children() as $simplexml_child) {
119
            if (count($simplexml_child->children()) === 0) {
120
                if (!isset($simplexml_to->{$simplexml_child->getName()})) {
121
                    $simplexml_to->addChild($simplexml_child->getName(), htmlspecialchars((string)$simplexml_child));
122
                } elseif(count($simplexml_to->{$simplexml_child->getName()}->children()) === 0) {
123
                    $simplexml_to->{$simplexml_child->getName()} = htmlspecialchars((string)$simplexml_child);
124
                }
125
            } else {
126
                $this->appendSimplexml($simplexml_to->{$simplexml_child->getName()}, $simplexml_child, $replace);
0 ignored issues
show
Bug introduced by
The variable $replace does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Unused Code introduced by
The call to Xml::appendSimplexml() has too many arguments starting with $replace.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
127
            }
128
            $attrs = $simplexml_to->{$simplexml_child->getName()}->attributes();
129
            foreach ($simplexml_child->attributes() as $attr_key => $attr_value) {
130
                if (!isset($attrs[$attr_key])) {
131
                    $simplexml_to->{$simplexml_child->getName()}->addAttribute($attr_key, (string)$attr_value);
132
                } else {
133
                    $simplexml_to->{$simplexml_child->getName()}->attributes()->{$attr_key} = (string)$attr_value;
134
                }
135
            }
136
        }
137
138
        return true;
139
    }
140
141
142
    /**
143
     * Get entire simplexml
144
     *
145
     * @return SimpleXMLElement
146
     */
147
    public function getRaw(): SimpleXMLElement
148
    {
149
        return $this->store;
150
    }
151
152
153
    /**
154
     * Get from config
155
     *
156
     * @param   string $name
157
     * @return  SimpleXMLElement
158
     */
159
    public function __get(string $name): SimpleXMLElement
160
    {
161
        return $this->store->{$name};
162
    }
163
164
165
    /**
166
     * Add config tree and merge it
167
     *
168
     * @param   ConfigInterface $config
169
     * @return  ConfigInterface
170
     */
171
    public function merge($config): ConfigInterface
172
    {
173
        $merge = $config->getRaw();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Micro\Config\ConfigInterface as the method getRaw() does only exist in the following implementations of said interface: Micro\Config\Xml.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
174
        $this->appendSimplexml($this->store, $merge);
175
176
        $result = $this->store->xpath('//*[@reference]');
177
        while (list(, $node) = each($result)) {
178
            $path = (string)$node->attributes()->reference;
179
180
            if ($path === '') {
181
                continue;
182
            }
183
184
            $xpath = '//'.str_replace('.', '/', $path);
185
            $found = $this->store->xpath($xpath);
186
            if (count($found) !== 1) {
187
                continue;
188
            }
189
190
            $found = array_shift($found);
191
            $this->appendSimplexml($node, $found);
192
        }
193
194
        return $this;
195
    }
196
197
198
    /**
199
     * Get xml as config
200
     *
201
     * @param   SimpleXMLElement $xml
202
     * @return  Config
203
     */
204
    public function map(?SimpleXMLElement $xml = null): Config
205
    {
206
        if ($xml === null) {
207
            $xml = $this->store;
208
        }
209
210
        $config = new Config();
211
        foreach ($xml->getNamespaces() + [null] as $prefix => $namespace) {
212
            if($prefix === self::CONFIG_FEATURE_NAMESPACE_PREFIX) {
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison === seems to always evaluate to false as the types of $prefix (integer) and self::CONFIG_FEATURE_NAMESPACE_PREFIX (string) can never be identical. Maybe you want to use a loose comparison == instead?
Loading history...
213
                continue;
214
            }
215
216
            foreach ($xml->attributes($namespace) as $key => $value) {
217
                if (is_string($prefix)) {
218
                    $key = $prefix.'.'.$key;
219
                }
220
221
                if ($key === 'reference') {
222
                    continue;
223
                }
224
225
                $config[$key] = (string)$value;
226
            }
227
        }
228
229
        foreach ($xml as $name => $element) {
230
            if(isset($element->attributes(self::CONFIG_FEATURE_NAMESPACE)->name)) {
231
                $name = (string)$element->attributes(self::CONFIG_FEATURE_NAMESPACE)->name;
232
            }
233
234
            $value = $element->children() ? $this->map($element) : trim((string)$element);
235
            if ($value || $value === '0') {
236
                if (!isset($arr[$name])) {
237
                    $config[$name] = $value;
238
                } else {
239
                    foreach ((array)$value as $k => $v) {
240
                        if (is_numeric($k)) {
241
                            $config[$name][] = $v;
242
                        } else {
243
                            $config[$name][$k] = array_merge(
244
                                (array)$config[$name][$k],
245
                                (array)$v
246
                            );
247
                        }
248
                    }
249
                }
250
            } else {
251
                $config[$name] = new Config();
252
            }
253
        }
254
        if ($content = trim((string)$xml)) {
255
            $config[] = $content;
256
        }
257
258
        return $config;
259
    }
260
}
261