Completed
Push — master ( c40f08...8b7387 )
by Garrett
02:30
created

Dice::expand()   C

Complexity

Conditions 11
Paths 22

Size

Total Lines 38
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 38
rs 5.2653
c 0
b 0
f 0
cc 11
eloc 16
nc 22
nop 3

How to fix   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
/**
4
 * @description Dice - A minimal Dependency Injection Container for PHP
5
 *
6
 * @author      Tom Butler [email protected]
7
 * @author      Garrett Whitehorn http://garrettw.net/
8
 * @copyright   2012-2015 Tom Butler <[email protected]> | https://r.je/dice.html
9
 * @license     http://www.opensource.org/licenses/bsd-license.php  BSD License
10
 *
11
 * @version     2.0
12
 */
13
14
namespace Dice;
15
16
class Dice
17
{
18
    /**
19
     * @var array $rules Rules which have been set using addRule()
20
     */
21
    private $rules = [];
22
23
    /**
24
     * @var array $cache A cache of closures based on class name so each class is only reflected once
25
     */
26
    private $cache = [];
27
28
    /**
29
     * @var array $instances Stores any instances marked as 'shared' so create() can return the same instance
30
     */
31
    private $instances = [];
32
33
    /**
34
     * Constructor which allows setting a default ruleset to apply to all objects.
35
     */
36
    public function __construct($defaultRule = [])
37
    {
38
        if (!empty($defaultRule)) {
39
            $this->rules['*'] = $defaultRule;
40
        }
41
    }
42
43
    /**
44
     * Adds a rule $rule to the class $classname.
45
     *
46
     * The container can be fully configured using rules provided by associative arrays.
47
     * See {@link https://r.je/dice.html#example3} for a description of the rules.
48
     *
49
     * @param string $classname The name of the class to add the rule for
50
     * @param array $rule The rule to add to it
51
     */
52
    public function addRule($classname, $rule, $swap = false)
53
    {
54
        if ($swap) {
55
            $temp = $rule;
56
            $rule = $classname;
57
            $classname = $temp;
58
        }
59
        $this->rules[self::normalizeName($classname)] = \array_merge_recursive($this->getRule($classname), $rule);
0 ignored issues
show
Bug introduced by
It seems like $classname defined by $temp on line 57 can also be of type array; however, Dice\Dice::getRule() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
60
    }
61
62
    /**
63
     * Returns the rule that will be applied to the class $matching during create().
64
     *
65
     * @param string $name The name of the ruleset to get - can be a class or not
66
     * @return array Ruleset that applies when instantiating the given name
67
     */
68
    public function getRule($name)
69
    {
70
        // first, check for exact match
71
        $normalname = self::normalizeName($name);
72
73
        if (isset($this->rules[$normalname])) {
74
            return $this->rules[$normalname];
75
        }
76
77
        // next, look for a rule where:
78
        foreach ($this->rules as $key => $rule) {
79
            if ($key !== '*'                    // it's not the default rule,
80
                && \is_subclass_of($name, $key) // its name is a parent class of what we're looking for,
81
                && empty($rule['instanceOf'])   // it's not a named instance,
82
                && (!array_key_exists('inherit', $rule) || $rule['inherit'] === true) // and it applies to subclasses
83
            ) {
84
                return $rule;
85
            }
86
        }
87
88
        // if we get here, return the default rule if it's set
89
        return (isset($this->rules['*'])) ? $this->rules['*'] : [];
90
    }
91
92
    /**
93
     * Returns a fully constructed object based on $classname using $args and $share as constructor arguments
94
     *
95
     * @param string $classname The name of the class to instantiate
96
     * @param array $args An array with any additional arguments to be passed into the constructor
97
     * @param array $share Whether the same class instance should be passed around each time
98
     * @return object A fully constructed object based on the specified input arguments
99
     */
100
    public function create($classname, array $args = [], array $share = [])
101
    {
102
        if (!empty($this->instances[$classname])) {
103
            // we've already created a shared instance so return it to save the closure call.
104
            return $this->instances[$classname];
105
        }
106
107
        // so now, we either need a new instance or just don't have one stored
108
        // but if we have the closure stored that creates it, call that
109
        if (!empty($this->cache[$classname])) {
110
            return $this->cache[$classname]($args, $share);
111
        }
112
113
        $rule = $this->getRule($classname);
114
        // Reflect the class for inspection, this should only ever be done once per class and then be cached
115
        $class = new \ReflectionClass(isset($rule['instanceOf']) ? $rule['instanceOf'] : $classname);
116
        $closure = $this->getClosure($classname, $rule, $class);
117
118
        //If there are shared instances, create them and merge them with shared instances higher up the object graph
119
        if (isset($rule['shareInstances'])) {
120
            $closure = function(array $args, array $share) use ($closure, $rule) {
121
                return $closure($args, array_merge($args, $share, array_map([$this, 'create'], $rule['shareInstances'])));
122
            };
123
        }
124
125
        // When $rule['call'] is set, wrap the closure in another closure which calls the required methods after constructing the object.
126
        // By putting this in a closure, the loop is never executed unless call is actually set.
127
        if (isset($rule['call'])) {
128
            $closure = function(array $args, array $share) use ($closure, $class, $rule) {
129
                // Construct the object using the original closure
130
                $object = $closure($args, $share);
131
132
                foreach ($rule['call'] as $call) {
133
                    // Generate the method arguments using getParams() and call the returned closure
134
                    // (in php7 it will be ()() rather than __invoke)
135
                    $shareRule = ['shareInstances' => isset($rule['shareInstances']) ? $rule['shareInstances'] : []];
136
                    $callMeMaybe = isset($call[1]) ? $call[1] : [];
137
                    call_user_func_array(
138
                        [$object, $call[0]],
139
                        $this->getParams($class->getMethod($call[0]), $shareRule)
140
                            ->__invoke($this->expand($callMeMaybe))
141
                    );
142
                }
143
144
                return $object;
145
            };
146
        }
147
148
        $this->cache[$classname] = $closure;
149
150
        return $this->cache[$classname]($args, $share);
151
    }
152
153
    /**
154
     * Returns a closure for creating object $name based on $rule, caching the reflection object for later use.
155
     *
156
     * The container can be fully configured using rules provided by associative arrays.
157
     * See {@link https://r.je/dice.html#example3} for a description of the rules.
158
     *
159
     * @param string $name The name of the class to get the closure for
160
     * @param array $rule The rule to base the instance on
161
     * @return callable A closure that will create the appropriate object when called
162
     */
163
    private function getClosure($name, array $rule, \ReflectionClass $class)
164
    {
165
        $constructor = $class->getConstructor();
166
        // Create parameter-generating closure in order to cache reflection on the parameters.
167
        // This way $reflectmethod->getParameters() only ever gets called once.
168
        $params = ($constructor) ? $this->getParams($constructor, $rule) : null;
169
170
        // Get a closure based on the type of object being created: shared, normal, or constructorless
171
        if (isset($rule['shared']) && $rule['shared'] === true) {
172
            return function(array $args, array $share) use ($name, $class, $constructor, $params) {
173
                if ($constructor) {
174
                    try {
175
                        // Shared instance: create without calling constructor (and write to \$name and $name, see issue #68)
176
                        $this->instances[$name] = $class->newInstanceWithoutConstructor();
177
                        // Now call constructor after constructing all dependencies. Avoids problems with cyclic references (issue #7)
178
                        $constructor->invokeArgs($this->instances[$name], $params($args, $share));
179
                    } catch (\ReflectionException $e) {
180
                        $this->instances[$name] = $class->newInstanceArgs($params($args, $share));
181
                    }
182
                } else {
183
                    $this->instances[$name] = $class->newInstanceWithoutConstructor();
184
                }
185
186
                $this->instances[self::normalizeNamespace($name)] = $this->instances[$name];
187
188
                return $this->instances[$name];
189
            };
190
        }
191
192
        if ($params) {
193
            // This class has dependencies, call the $params closure to generate them based on $args and $share
194
            return function(array $args, array $share) use ($class, $params) {
195
                return $class->newInstanceArgs($params($args, $share));
196
            };
197
        }
198
199
        return function() use ($class) {
200
            // No constructor arguments, just instantiate the class
201
            return new $class->name();
202
        };
203
    }
204
205
    /**
206
     * Returns a closure that generates arguments for $method based on $rule and any $args passed into the closure
207
     *
208
     * @param ReflectionMethod $method A reflection of the method to inspect
0 ignored issues
show
Documentation introduced by
Should the type for parameter $method not be \ReflectionMethod?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
209
     * @param array $rule The ruleset to use in interpreting what the params should be
210
     * @return callable A closure that uses the cached information to generate the method's arguments
211
     */
212
    private function getParams(\ReflectionMethod $method, array $rule)
213
    {
214
        $paramInfo = []; // Caches some information about the parameter so (slow) reflection isn't needed every time
215
        foreach ($method->getParameters() as $param) {
216
            // get the class hint of each param, if there is one
217
            $class = ($class = $param->getClass()) ? $class->name : null;
218
            // determine if the param can be null, if we need to substitute a
219
            // different class, or if we need to force a new instance for it
220
            $paramInfo[] = [
221
                $class,
222
                $param,
223
                isset($rule['substitutions']) && \array_key_exists($class, $rule['substitutions']),
224
            ];
225
        }
226
227
        // Return a closure that uses the cached information to generate the arguments for the method
228
        return function(array $args, array $share = []) use ($paramInfo, $rule) {
229
            // Now merge all the possible parameters: user-defined in the rule via constructParams,
230
            // shared instances, and the $args argument from $dice->create()
231
            if (!empty($share) || isset($rule['constructParams'])) {
232
                $args = \array_merge(
233
                    $args,
234
                    (isset($rule['constructParams'])) ? $this->expand($rule['constructParams'], $share) : [],
235
                    $share
236
                );
237
            }
238
239
            $parameters = [];
240
241
            // Now find a value for each method parameter
242
            foreach ($paramInfo as $pi) {
243
                list($class, $param, $sub) = $pi;
244
245
                // First, loop through $args and see if each value can match the current parameter based on type hint
246
                if (!empty($args)) { // This if statement actually gives a ~10% speed increase when $args isn't set
247
                    foreach ($args as $i => $arg) {
248
                        if ($class !== null
249
                            && ($arg instanceof $class || ($arg === null && $param->allowsNull()))
250
                        ) {
251
                            // The argument matches, store and remove from $args so it won't wrongly match another parameter
252
                            $parameters[] = \array_splice($args, $i, 1)[0];
253
                            continue 2; //Move on to the next parameter
254
                        }
255
                    }
256
                }
257
258
                // When nothing from $args matches but a class is type hinted, create an instance to use, using a substitution if set
259
                if ($class !== null) {
260
                    $parameters[] = ($sub)
261
                        ? $this->expand($rule['substitutions'][$class], $share, true)
262
                        : $this->create($class, [], $share);
263
                    continue;
264
                }
265
266
                // There is no type hint, so take the next available value from $args (and remove from $args to stop it being reused)
267
                if (!empty($args)) {
268
                    $parameters[] = $this->expand(\array_shift($args));
269
                    continue;
270
                }
271
272
                // There's no type hint and nothing left in $args, so provide the default value or null
273
                $parameters[] = ($param->isDefaultValueAvailable()) ? $param->getDefaultValue() : null;
274
            }
275
276
            //variadic functions will only have one argument. To account for those, append any remaining arguments to the list
277
            return array_merge($parameters, $args);
278
        };
279
    }
280
281
    /**
282
     * Looks for 'instance' array keys in $param, and when found, returns an object based on the value.
283
     * See {@link https:// r.je/dice.html#example3-1}
284
     *
285
     * @param string|array $param
286
     * @param array $share Whether this class instance will be passed around each time
287
     * @param bool $createFromString
288
     * @return mixed
289
     */
290
    private function expand($param, array $share = [], $createFromString = false)
291
    {
292
        if (!\is_array($param)) {
293
            // doesn't need any processing
294
            return (is_string($param) && $createFromString) ? $this->create($param) : $param;
295
        }
296
297
        if (!isset($param['instance'])) {
298
            // not a lazy instance, so recursively search for any 'instance' keys on deeper levels
299
            foreach ($param as $name => $value) {
300
                $param[$name] = $this->expand($value, $share);
301
            }
302
303
            return $param;
304
        }
305
306
        $args = isset($param['params']) ? $this->expand($param['params']) : [];
307
308
        // for ['instance' => ['className', 'methodName'] construct the instance before calling it
309
        if (\is_array($param['instance'])) {
310
            $param['instance'][0] = $this->expand($param['instance'][0], $share, true);
311
        }
312
313
        if (\is_callable($param['instance'])) {
314
            // it's a lazy instance formed by a function. Call or return the value stored under the key 'instance'
315
            if (isset($param['params'])) {
316
                return \call_user_func_array($param['instance'], $args);
317
            }
318
319
            return \call_user_func($param['instance']);
320
        }
321
322
        if (\is_string($param['instance'])) {
323
            // it's a lazy instance's class name string
324
            return $this->create($param['instance'], \array_merge($args, $share));
325
        }
326
        // if it's not a string, it's malformed. *shrug*
327
    }
328
329
    /**
330
     *
331
     */
332
    private static function normalizeName($name)
333
    {
334
        return \strtolower(self::normalizeNamespace($name));
335
    }
336
337
    /**
338
     *
339
     */
340
    private static function normalizeNamespace($name)
341
    {
342
        return \ltrim($name, '\\');
343
    }
344
}
345