Completed
Push — master ( c779b6...fe1a09 )
by Raffael
02:34
created

Container::createInstance()   C

Complexity

Conditions 8
Paths 4

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 6.6037
c 0
b 0
f 0
cc 8
eloc 12
nc 4
nop 3
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;
13
14
use \ReflectionClass;
15
use \Closure;
16
use \Micro\Container\Exception;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Micro\Exception.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
17
use \Micro\Container\AdapterAwareInterface;
18
19
class Container
20
{
21
    /**
22
     * Config
23
     *
24
     * @var array
25
     */
26
    protected $config;
27
28
29
    /**
30
     * Service registry
31
     *
32
     * @var array
33
     */
34
    protected $service = [];
35
36
37
    /**
38
     * Registered but not initialized service registry
39
     *
40
     * @var array
41
     */
42
    protected $registry = [];
43
44
45
    /**
46
     * Create container
47
     *
48
     * @param array $config
49
     */
50
    public function __construct(array $config=[])
51
    {
52
        $this->config = $config;
53
    }
54
55
56
    /**
57
     * Get service
58
     *
59
     * @param  string $name
60
     * @return mixed
61
     */
62
    public function get(string $name)
63
    {
64
        if($this->has($name)) {
65
            return $this->service[$name];
66
        } else {
67
            if(isset($this->registry[$name])) {
68
                $this->service[$name] = $this->registry[$name]->call($this);
69
                unset($this->registry[$name]);
70
                return $this->service[$name];
71
            } else {
72
                return $this->service[$name] = $this->autoWire($name);
73
            }
74
        }
75
    }
76
77
78
    /**
79
     * Add service
80
     *
81
     * @param  string $name
82
     * @param  Closure $service
83
     * @return Container
84
     */
85
    public function add(string $name, Closure $service): Container
86
    {
87
        if($this->has($name)) {
88
            throw new Exception('service '.$name.' is already registered');
89
        }
90
91
        $this->registry[$name] = $service;
92
        return $this;
93
    }
94
95
96
    /**
97
     * Check if service is registered
98
     *
99
     * @return bool
100
     */
101
    public function has(string $name): bool
102
    {
103
        return isset($this->service[$name]);
104
    }
105
106
107
    /**
108
     * Auto wire service
109
     *
110
     * @param  string $name
111
     * @return mixed
112
     */
113
    protected function autoWire(string $name)
114
    {
115
        if(isset($this->config[$name]) && isset($this->config[$name]['class'])) {
116
            $class = $this->config[$name]['class'];
117
        } else {
118
            $class = $name;
119
        }
120
121
        $reflection = new ReflectionClass($class);
122
        $constructor = $reflection->getConstructor();
123
124
        if($constructor === null) {
125
            return new $class();
126
        } else {
127
            $params = $constructor->getParameters();
128
            $args = [];
129
130
            foreach($params as $param) {
131
                $type = $param->getClass();
132
                $param_name = $param->getName();
133
134
                if($type === null) {
135
                    try {
136
                        $args[$param_name] = $this->getParam($name, $param_name);
137
                    } catch(Exception $e) {
138
                        if($param->isDefaultValueAvailable()) {
139
                            $args[$param_name] = $param->getDefaultValue();
140
                        } else {
141
                            throw $e;
142
                        }
143
                    }
144
                } else {
145
                    $type_class = $type->getName();
146
                    $args[$type_class] = $this->get($type_class);
147
                }
148
            }
149
150
            return $this->createInstance($name, $reflection, $args);
151
        }
152
    }
153
154
155
    /**
156
     * Create instance
157
     *
158
     * @param  string $name
159
     * @param  ReflectionClass $class
160
     * @param  array $args
161
     * @return mixed
162
     */
163
    protected function createInstance(string $name, ReflectionClass $class, array $args)
164
    {
165
        $instance = $class->newInstanceArgs($args);
166
        if($instance instanceof AdapterAwareInterface) {
167
            if(isset($this->config[$name]) && isset($this->config[$name]['adapter'])) {
168
                foreach($this->config[$name]['adapter'] as $adapter => $config) {
169
                    if(!isset($config['class'])) {
170
                        throw new Exception('adapter requires class configuration');
171
                    }
172
173
                    if(isset($config['enabled']) && $config['enabled'] === '0') {
174
                        continue;
175
                    }
176
177
                    $adapter_instance = $this->get($config['class']);
178
                    $instance->injectAdapter($adapter, $adapter_instance);
179
                }
180
            }
181
        }
182
183
        return $instance;
184
    }
185
186
187
    /**
188
     * Get config value
189
     *
190
     * @param  string $name
191
     * @param  string $param
192
     * @return mixed
193
     */
194
    public function getParam(string $name, string $param)
195
    {
196 View Code Duplication
        if(!isset($this->config[$name]) && !isset($this->config[$name]['options'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
197
            throw new Exception('no configuration available for service '.$name);
198
        }
199
200 View Code Duplication
        if(!isset($this->config[$name]['options'][$param])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
201
            throw new Exception('no configuration available for service parameter '.$param);
202
        }
203
204
        return $this->config[$name]['options'][$param];
205
    }
206
}
207