Completed
Pull Request — master (#14)
by Rasmus
01:26
created

Container::initialize()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 13
cts 13
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 9
nc 4
nop 1
crap 4
1
<?php
2
3
namespace mindplay\unbox;
4
5
use Interop\Container\ContainerInterface;
6
use Psr\Container\ContainerInterface as PsrContainerInterface;
7
use InvalidArgumentException;
8
use ReflectionClass;
9
use ReflectionFunction;
10
use ReflectionParameter;
11
12
/**
13
 * This class implements a simple dependency injection container.
14
 */
15
class Container extends Configuration implements ContainerInterface, FactoryInterface
16
{
17
    /**
18
     * @var bool[] map where component name => TRUE, if the component has been initialized
19
     */
20
    protected $active = [];
21
22
    /**
23
     * @param Configuration $config
24
     */
25 1
    public function __construct(Configuration $config)
26
    {
27 1
        $config->copyTo($this);
28
29 1
        $this->values = $this->values +
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->values + array(ge...erface::class => $this) of type array<integer|string,*> is incompatible with the declared type array<integer,*> of property $values.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
30
            [
31 1
                get_class($this)             => $this,
32 1
                __CLASS__                    => $this,
33 1
                PsrContainerInterface::class => $this,
34 1
                ContainerInterface::class    => $this,
35 1
                FactoryInterface::class      => $this,
36 1
            ];
37 1
    }
38
39
    /**
40
     * Resolve the registered component with the given name.
41
     *
42
     * @param string $name component name
43
     *
44
     * @return mixed
45
     *
46
     * @throws ContainerException
47
     * @throws NotFoundException
48
     */
49 1
    public function get($name)
50
    {
51 1
        if (! isset($this->active[$name])) {
52 1
            if (isset($this->factory[$name])) {
53 1
                $factory = $this->factory[$name];
54
55 1
                $reflection = new ReflectionFunction($factory);
56
57 1
                $params = $this->resolve($reflection->getParameters(), $this->factory_map[$name]);
58
59 1
                $this->values[$name] = call_user_func_array($factory, $params);
60 1
            } elseif (! array_key_exists($name, $this->values)) {
61 1
                throw new NotFoundException($name);
62
            }
63
64 1
            $this->active[$name] = true;
65
66 1
            $this->initialize($name);
67 1
        }
68
69 1
        return $this->values[$name];
70
    }
71
72
    /**
73
     * Check for the existence of a component with a given name.
74
     *
75
     * @param string $name component name
76
     *
77
     * @return bool true, if a component with the given name has been defined
78
     */
79 1
    public function has($name)
80
    {
81 1
        return array_key_exists($name, $this->values) || isset($this->factory[$name]);
82
    }
83
84
    /**
85
     * Check if a component has been unboxed and is currently active.
86
     *
87
     * @param string $name component name
88
     *
89
     * @return bool
90
     */
91 1
    public function isActive($name)
92
    {
93 1
        return isset($this->active[$name]);
94
    }
95
96
    /**
97
     * Call any given callable, using dependency injection to satisfy it's arguments, and/or
98
     * manually specifying some of those arguments - then return the value from the call.
99
     *
100
     * This will work for any callable:
101
     *
102
     *     $container->call('foo');               // function foo()
103
     *     $container->call($foo, 'baz');         // instance method $foo->baz()
104
     *     $container->call([Foo::class, 'bar']); // static method Foo::bar()
105
     *     $container->call($foo);                // closure (or class implementing __invoke)
106
     *
107
     * In any of those examples, you can also supply custom arguments, either named or
108
     * positional, or mixed, as per the `$map` argument in `register()`, `configure()`, etc.
109
     *
110
     * See also {@see create()} which lets you invoke any constructor.
111
     *
112
     * @param callable|object $callback any arbitrary closure or callable, or object implementing __invoke()
113
     * @param mixed|mixed[]   $map      mixed list/map of parameter values (and/or boxed values)
114
     *
115
     * @return mixed return value from the given callable
116
     */
117 1
    public function call($callback, $map = [])
118
    {
119 1
        $params = Reflection::createFromCallable($callback)->getParameters();
120
121 1
        return call_user_func_array($callback, $this->resolve($params, $map));
122
    }
123
124
    /**
125
     * Create an instance of a given class.
126
     *
127
     * The container will internally resolve and inject any constructor arguments
128
     * not explicitly provided in the (optional) second parameter.
129
     *
130
     * @param string        $class_name fully-qualified class-name
131
     * @param mixed|mixed[] $map        mixed list/map of parameter values (and/or boxed values)
132
     *
133
     * @return mixed
134
     */
135 1
    public function create($class_name, $map = [])
136
    {
137 1
        if (! class_exists($class_name)) {
138 1
            throw new InvalidArgumentException("unable to create component: {$class_name}");
139
        }
140
141 1
        $reflection = new ReflectionClass($class_name);
142
143 1
        if (! $reflection->isInstantiable()) {
144 1
            throw new InvalidArgumentException("unable to create instance of abstract class: {$class_name}");
145
        }
146
147 1
        $constructor = $reflection->getConstructor();
148
149
        $params = $constructor
150 1
            ? $this->resolve($constructor->getParameters(), $map, false)
151 1
            : [];
152
153 1
        return $reflection->newInstanceArgs($params);
154
    }
155
156
    /**
157
     * Internally resolves parameters to functions or constructors.
158
     *
159
     * This is the heart of the beast.
160
     *
161
     * @param ReflectionParameter[] $params parameter reflections
162
     * @param array                 $map    mixed list/map of parameter values (and/or boxed values)
163
     * @param bool                  $safe   if TRUE, it's considered safe to resolve against parameter names
164
     *
165
     * @return array parameters
166
     *
167
     * @throws ContainerException
168
     * @throws NotFoundException
169
     */
170 1
    protected function resolve(array $params, $map, $safe = true)
171
    {
172 1
        $args = [];
173
174 1
        foreach ($params as $index => $param) {
175 1
            $param_name = $param->name;
176
177 1
            if (array_key_exists($param_name, $map)) {
178 1
                $value = $map[$param_name]; // // resolve as user-provided named argument
179 1
            } elseif (array_key_exists($index, $map)) {
180 1
                $value = $map[$index]; // resolve as user-provided positional argument
181 1
            } else {
182
                // as on optimization, obtain the argument type without triggering autoload:
183
184 1
                $type = Reflection::getParameterType($param);
185
186 1
                if ($type && isset($map[$type])) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $type of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
187 1
                    $value = $map[$type]; // resolve as user-provided type-hinted argument
188 1
                } elseif ($type && $this->has($type)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $type of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
189 1
                    $value = $this->get($type); // resolve as component registered by class/interface name
190 1
                } elseif ($safe && $this->has($param_name)) {
191 1
                    $value = $this->get($param_name); // resolve as component with matching parameter name
192 1
                } elseif ($param->isOptional()) {
193 1
                    $value = $param->getDefaultValue(); // unresolved, optional: resolve using default value
194 1
                } elseif ($type && $param->allowsNull()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $type of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
195
                    $value = null; // unresolved, type-hinted, nullable: resolve as NULL
196
                } else {
197
                    // unresolved - throw a container exception:
198
199 1
                    $reflection = $param->getDeclaringFunction();
200
201 1
                    throw new ContainerException(
202 1
                        "unable to resolve parameter: \${$param_name} " . ($type ? "({$type}) " : "") .
203 1
                        "in file: " . $reflection->getFileName() . ", line " . $reflection->getStartLine()
204 1
                    );
205
                }
206
            }
207
208 1
            if ($value instanceof BoxedValueInterface) {
209 1
                $value = $value->unbox($this); // unbox a boxed value
210 1
            }
211
212 1
            $args[] = $value; // argument resolved!
213 1
        }
214
215 1
        return $args;
216
    }
217
218
    /**
219
     * Dynamically inject a component into this Container.
220
     *
221
     * Enables classes that extend `Container` to dynamically inject components (to implement "auto-wiring")
222
     *
223
     * @param string $name
224
     * @param mixed  $value
225
     */
226 1
    protected function inject($name, $value)
227
    {
228 1
        $this->values[$name] = $value;
229 1
        $this->active[$name] = true;
230 1
    }
231
232
    /**
233
     * Internally initialize an active component.
234
     *
235
     * @param string $name component name
236
     *
237
     * @return void
238
     */
239 1
    private function initialize($name)
240
    {
241 1
        if (isset($this->config[$name])) {
242 1
            foreach ($this->config[$name] as $index => $config) {
243 1
                $map = $this->config_map[$name][$index];
244
245 1
                $reflection = Reflection::createFromCallable($config);
246
247 1
                $params = $this->resolve($reflection->getParameters(), $map);
0 ignored issues
show
Documentation introduced by
$map is of type callable, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
248
249 1
                $value = call_user_func_array($config, $params);
250
251 1
                if ($value !== null) {
252 1
                    $this->values[$name] = $value;
253 1
                }
254 1
            }
255 1
        }
256 1
    }
257
}
258