Completed
Push — 5.x ( 6325ad...bea55e )
by Lars
05:35
created

Swift_DependencyContainer::_lookupRecursive()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3
Metric Value
dl 0
loc 13
ccs 7
cts 7
cp 1
rs 9.4285
cc 3
eloc 7
nc 3
nop 1
crap 3
1
<?php
2
3
/*
4
 * This file is part of SwiftMailer.
5
 * (c) 2004-2009 Chris Corbyn
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
/**
12
 * Dependency Injection container.
13
 *
14
 * @author Chris Corbyn
15
 */
16
class Swift_DependencyContainer
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
17
{
18
    /**
19
     * Constant for literal value types
20
     */
21
    const TYPE_VALUE = 0x0001;
22
23
    /**
24
     * Constant for new instance types
25
     */
26
    const TYPE_INSTANCE = 0x0010;
27
28
    /**
29
     * Constant for shared instance types
30
     */
31
    const TYPE_SHARED = 0x0100;
32
33
    /**
34
     * Constant for aliases
35
     */
36
    const TYPE_ALIAS = 0x1000;
37
38
    /**
39
     * Singleton instance
40
     *
41
     * @var null|self
42
     */
43
    private static $_instance = null;
44
45
    /**
46
     * The data container
47
     *
48
     * @var array
49
     */
50
    private $_store = array();
51
52
    /**
53
     * The current endpoint in the data container
54
     */
55
    private $_endPoint;
56
57
    /**
58
     * Constructor should not be used.
59
     *
60
     * Use {@link getInstance()} instead.
61
     */
62 18
    public function __construct()
63
    {
64 18
    }
65
66
    /**
67
     * Returns a singleton of the DependencyContainer.
68
     *
69
     * @return Swift_DependencyContainer
70
     */
71 138
    public static function getInstance()
72
    {
73 138
        if (!isset(self::$_instance)) {
74
            self::$_instance = new self();
75
        }
76
77 138
        return self::$_instance;
78
    }
79
80
    /**
81
     * List the names of all items stored in the Container.
82
     *
83
     * @return array
84
     */
85 1
    public function listItems()
86
    {
87 1
        return array_keys($this->_store);
88
    }
89
90
    /**
91
     * Test if an item is registered in this container with the given name.
92
     *
93
     * @see register()
94
     *
95
     * @param string $itemName
96
     *
97
     * @return bool
98
     */
99 156
    public function has($itemName)
100
    {
101 156
        return isset($this->_store[$itemName]) && isset($this->_store[$itemName]['lookupType']);
102
    }
103
104
    /**
105
     * Lookup the item with the given $itemName.
106
     *
107
     * @see register()
108
     *
109
     * @param string $itemName
110
     *
111
     * @throws Swift_DependencyException If the dependency is not found
112
     *
113
     * @return mixed
114
     */
115 152
    public function lookup($itemName)
116
    {
117 152
        if (!$this->has($itemName)) {
118
            throw new Swift_DependencyException(
119
                'Cannot lookup dependency "' . $itemName . '" since it is not registered.'
120
            );
121
        }
122
123 152
        switch ($this->_store[$itemName]['lookupType']) {
124 152
            case self::TYPE_ALIAS:
125 134
                return $this->_createAlias($itemName);
126 152
            case self::TYPE_VALUE:
127 144
                return $this->_getValue($itemName);
128 149
            case self::TYPE_INSTANCE:
129 146
                return $this->_createNewInstance($itemName);
130 137
            case self::TYPE_SHARED:
131 137
                return $this->_createSharedInstance($itemName);
132
        }
133
    }
134
135
    /**
136
     * Create an array of arguments passed to the constructor of $itemName.
137
     *
138
     * @param string $itemName
139
     *
140
     * @return array
141
     */
142 148
    public function createDependenciesFor($itemName)
143
    {
144 148
        $args = array();
145 148
        if (isset($this->_store[$itemName]['args'])) {
146 144
            $args = $this->_resolveArgs($this->_store[$itemName]['args']);
147
        }
148
149 148
        return $args;
150
    }
151
152
    /**
153
     * Register a new dependency with $itemName.
154
     *
155
     * This method returns the current DependencyContainer instance because it
156
     * requires the use of the fluid interface to set the specific details for the
157
     * dependency.
158
     *
159
     * @see asNewInstanceOf(), asSharedInstanceOf(), asValue()
160
     *
161
     * @param string $itemName
162
     *
163
     * @return Swift_DependencyContainer
164
     */
165 103
    public function register($itemName)
166
    {
167 103
        $this->_store[$itemName] = array();
168 103
        $this->_endPoint = &$this->_store[$itemName];
169
170 103
        return $this;
171
    }
172
173
    /**
174
     * Specify the previously registered item as a literal value.
175
     *
176
     * {@link register()} must be called before this will work.
177
     *
178
     * @param mixed $value
179
     *
180
     * @return Swift_DependencyContainer
181
     */
182 94
    public function asValue($value)
183
    {
184 94
        $endPoint = &$this->_getEndPoint();
185 94
        $endPoint['lookupType'] = self::TYPE_VALUE;
186 94
        $endPoint['value'] = $value;
187
188 94
        return $this;
189
    }
190
191
    /**
192
     * Specify the previously registered item as an alias of another item.
193
     *
194
     * @param string $lookup
195
     *
196
     * @return Swift_DependencyContainer
197
     */
198 2
    public function asAliasOf($lookup)
199
    {
200 2
        $endPoint = &$this->_getEndPoint();
201 2
        $endPoint['lookupType'] = self::TYPE_ALIAS;
202 2
        $endPoint['ref'] = $lookup;
203
204 2
        return $this;
205
    }
206
207
    /**
208
     * Specify the previously registered item as a new instance of $className.
209
     *
210
     * {@link register()} must be called before this will work.
211
     * Any arguments can be set with {@link withDependencies()},
212
     * {@link addConstructorValue()} or {@link addConstructorLookup()}.
213
     *
214
     * @see withDependencies(), addConstructorValue(), addConstructorLookup()
215
     *
216
     * @param string $className
217
     *
218
     * @return Swift_DependencyContainer
219
     */
220 12 View Code Duplication
    public function asNewInstanceOf($className)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
221
    {
222 12
        $endPoint = &$this->_getEndPoint();
223 12
        $endPoint['lookupType'] = self::TYPE_INSTANCE;
224 12
        $endPoint['className'] = $className;
225
226 12
        return $this;
227
    }
228
229
    /**
230
     * Specify the previously registered item as a shared instance of $className.
231
     *
232
     * {@link register()} must be called before this will work.
233
     *
234
     * @param string $className
235
     *
236
     * @return Swift_DependencyContainer
237
     */
238 3 View Code Duplication
    public function asSharedInstanceOf($className)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
239
    {
240 3
        $endPoint = &$this->_getEndPoint();
241 3
        $endPoint['lookupType'] = self::TYPE_SHARED;
242 3
        $endPoint['className'] = $className;
243
244 3
        return $this;
245
    }
246
247
    /**
248
     * Specify a list of injected dependencies for the previously registered item.
249
     *
250
     * This method takes an array of lookup names.
251
     *
252
     * @see addConstructorValue(), addConstructorLookup()
253
     *
254
     * @param array $lookups
255
     *
256
     * @return Swift_DependencyContainer
257
     */
258 7
    public function withDependencies(array $lookups)
259
    {
260 7
        $endPoint = &$this->_getEndPoint();
261 7
        $endPoint['args'] = array();
262 7
        foreach ($lookups as $lookup) {
263 7
            $this->addConstructorLookup($lookup);
264
        }
265
266 7
        return $this;
267
    }
268
269
    /**
270
     * Specify a literal (non looked up) value for the constructor of the
271
     * previously registered item.
272
     *
273
     * @see withDependencies(), addConstructorLookup()
274
     *
275
     * @param mixed $value
276
     *
277
     * @return Swift_DependencyContainer
278
     */
279 3 View Code Duplication
    public function addConstructorValue($value)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
280
    {
281 3
        $endPoint = &$this->_getEndPoint();
282 3
        if (!isset($endPoint['args'])) {
283 1
            $endPoint['args'] = array();
284
        }
285 3
        $endPoint['args'][] = array('type' => 'value', 'item' => $value);
286
287 3
        return $this;
288
    }
289
290
    /**
291
     * Specify a dependency lookup for the constructor of the previously
292
     * registered item.
293
     *
294
     * @see withDependencies(), addConstructorValue()
295
     *
296
     * @param string $lookup
297
     *
298
     * @return Swift_DependencyContainer
299
     */
300 8 View Code Duplication
    public function addConstructorLookup($lookup)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
301
    {
302 8
        $endPoint = &$this->_getEndPoint();
303 8
        if (!isset($this->_endPoint['args'])) {
304 1
            $endPoint['args'] = array();
305
        }
306 8
        $endPoint['args'][] = array('type' => 'lookup', 'item' => $lookup);
307
308 8
        return $this;
309
    }
310
311
    /**
312
     * Get the literal value with $itemName
313
     *
314
     * @param $itemName
315
     *
316
     * @return mixed
317
     */
318 144
    private function _getValue($itemName)
319
    {
320 144
        return $this->_store[$itemName]['value'];
321
    }
322
323
    /**
324
     * Resolve an alias to another item
325
     *
326
     * @param $itemName
327
     *
328
     * @return mixed
329
     * @throws Swift_DependencyException
330
     */
331 134
    private function _createAlias($itemName)
332
    {
333 134
        return $this->lookup($this->_store[$itemName]['ref']);
334
    }
335
336
    /** Create a fresh instance of $itemName */
337 148
    private function _createNewInstance($itemName)
338
    {
339 148
        $reflector = new ReflectionClass($this->_store[$itemName]['className']);
340 148
        if ($reflector->getConstructor()) {
341 148
            return $reflector->newInstanceArgs(
342 148
                $this->createDependenciesFor($itemName)
343
            );
344
        }
345
346 15
        return $reflector->newInstance();
347
    }
348
349
    /**
350
     * Create and register a shared instance of $itemName
351
     *
352
     * @param $itemName
353
     *
354
     * @return mixed
355
     */
356 137
    private function _createSharedInstance($itemName)
357
    {
358 137
        if (!isset($this->_store[$itemName]['instance'])) {
359 6
            $this->_store[$itemName]['instance'] = $this->_createNewInstance($itemName);
360
        }
361
362 137
        return $this->_store[$itemName]['instance'];
363
    }
364
365
    /**
366
     * Get the current endpoint in the store
367
     *
368
     * @return mixed
369
     */
370 103
    private function &_getEndPoint()
371
    {
372 103
        if (!isset($this->_endPoint)) {
373
            throw new BadMethodCallException(
374
                'Component must first be registered by calling register()'
375
            );
376
        }
377
378 103
        return $this->_endPoint;
379
    }
380
381
    /**
382
     * Get an argument list with dependencies resolved
383
     *
384
     * @param array $args
385
     *
386
     * @return array
387
     */
388 144
    private function _resolveArgs(array $args)
389
    {
390 144
        $resolved = array();
391 144
        foreach ($args as $argDefinition) {
392 144
            switch ($argDefinition['type']) {
393 144
                case 'lookup':
394 141
                    $resolved[] = $this->_lookupRecursive($argDefinition['item']);
395 141
                    break;
396 85
                case 'value':
397 85
                    $resolved[] = $argDefinition['item'];
398 144
                    break;
399
            }
400
        }
401
402 144
        return $resolved;
403
    }
404
405
    /** Resolve a single dependency with an collections */
406 141
    private function _lookupRecursive($item)
407
    {
408 141
        if (is_array($item)) {
409 6
            $collection = array();
410 6
            foreach ($item as $k => $v) {
411 6
                $collection[$k] = $this->_lookupRecursive($v);
412
            }
413
414 6
            return $collection;
415
        }
416
417 141
        return $this->lookup($item);
418
    }
419
}
420