beberlei / yadif forked from tsmckelvey/yadif

Yet Another (PHP) Dependency Injection Framework

This URL has Read+Write access

yadif / Container.php
100644 541 lines (474 sloc) 16.323 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
<?php
/**
* Yadif
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to tsmckelvey@gmail.com so I can send you a copy immediately.
*/
 
require_once 'Exception.php';
 
/**
* Yadif_Container
*
* @category Yadif
* @copyright Copyright (c) 2008 Thomas McKelvey
* @copyright Copyright (c) 2009 Benjamin Eberlei
* @author Thomas McKelvey (http://github.com/tsmckelvey/yadif/tree/master)
* @author Benjamin Eberlei (http://github.com/beberlei/yadif/tree/master)
*/
class Yadif_Container
{
    const CHAR_CONFIG_VALUE = '%';
    const CHAR_ARGUMENT = ':';
 
    /**
* Identifier for singleton scope
*/
    const SCOPE_SINGLETON = "singleton";
 
    /**
* Identifier for prototype scope (new object each call)
*/
    const SCOPE_PROTOTYPE = "prototype";
 
    /**
* Class index key of component $config
*/
    const CONFIG_CLASS = 'class';
 
    /**
* Arguments index key of component $config
*/
    const CONFIG_ARGUMENTS = 'arguments';
 
    /**
* Parameters
*/
    const CONFIG_PARAMETERS = 'params';
 
    /**
* Singleton index key of component $config
*/
    const CONFIG_SCOPE = 'scope';
 
    /**
* Setter Methods to call config index key
*/
    const CONFIG_METHODS = 'methods';
 
    /**
* Method Name
*/
    const CONFIG_METHOD = 'method';
 
    /**
* Factory Config key for classes that are instantiated via a static factory method
*/
    const CONFIG_FACTORY = 'factory';
 
    /**
* container of component configurations
*
* @var array
*/
    protected $_container = array();
 
    /**
* parameters which have been set, expected to be bound
*
* @var array
*/
    protected $_parameters = array();
 
    /**
* All managed instances inside this container which are not Scoped "Prototype"
*
* @var array
*/
    protected $_instances = array();
 
    /**
* Config
*
* @var Zend_Config
*/
    protected $_config = null;
 
    /**
* Construct Dependency Injection Container
*
* @param Zend_Config|array $components
* @param Zend_Config $config
*/
    public function __construct($components = array(), Zend_Config $config=null)
    {
        $this->addComponents($components);
        $this->setConfig($config);
    }
 
    /**
* Set Config object
*
* @param Zend_Config $config
* @return Yadif_Container
*/
    public function setConfig(Zend_Config $config=null)
    {
        $this->_config = $config;
        return $this;
    }
 
    /**
* Getter method for internal array of component configurations
*
* @return array
*/
    public function getContainer()
    {
        return $this->_container;
    }
 
    /**
* Getter method for internal array of parameters
*
* @return array
*/
    public function getParameters()
    {
        return $this->_parameters;
    }
 
    /**
* Get currently managed instances of the container.
*
* In its current implementations only the singleton scoped objects are returned,
* but in an implementation with additional session scope it is necessary to return
* also those from this function.
*
* @return array
*/
    public function getInstances()
    {
        return $this->_instances;
    }
 
    /**
* Get Config inside this Container
*
* @return Zend_Config|null
*/
    public function getConfig()
    {
        return $this->_config;
    }
 
    /**
* Merge two Containers
*
* @todo Handle duplicates, currently array_merge overwrites them
* @param Yadif_Container $container
* @return Yadif_Container
*/
    public function merge(Yadif_Container $container)
    {
        $this->_container = array_merge($this->_container, $container->getContainer());
        $this->_instances = array_merge($this->_instances, $container->getInstances());
 
        $otherConfig = $container->getConfig();
        $ownConfig = $this->getConfig();
        if($otherConfig instanceof Zend_Config) {
            if($ownConfig == null) {
                $this->setConfig($otherConfig);
            } else {
                if($ownConfig->readOnly() == true) {
                    $this->setConfig(new Zend_Config(array_merge($ownConfig->toArray(), $otherConfig->toArray())));
                } else {
                    $this->setConfig($ownConfig->merge($otherConfig));
                }
            }
        }
 
        return $this;
    }
 
    /**
* Add several components to the container via a config.
*
* @param array|Zend_Config $components
* @return Yadif_Container
*/
    public function addComponents($components)
    {
        if($components instanceof Zend_Config) {
            $components = $components->toArray();
        }
 
        if (isset($components) && is_array($components)) {
            foreach ($components as $componentName => $componentConfig) {
                $this->addComponent( $componentName, $componentConfig );
            }
        }
    }
 
    /**
* Add a component to the container
*
* If $config is omitted, $name is assumed to be the classname.
*
* @param string|Yadif_Container $name Class-tag, class, or Yadif_Container
* @param array $config Array of configuration values
* @return Yadif_Container
*/
    public function addComponent($name = null, array $config = null)
    {
        if ($name instanceof Yadif_Container) { // if Yadif_Container
            $this->merge($name);
        } elseif(is_string($name)) {
            if (!is_array($config) || !isset($config[self::CONFIG_CLASS])) { // assume name is the class name
                $config[self::CONFIG_CLASS] = $name;
            }
 
            if (!isset($config[self::CONFIG_ARGUMENTS]) || !is_array($config[self::CONFIG_ARGUMENTS])) {
                $config[ self::CONFIG_ARGUMENTS ] = array();
            }
 
            if(!isset($config[self::CONFIG_PARAMETERS])) {
                $config[self::CONFIG_PARAMETERS] = array();
            }
 
            // if class is set and doesn't exist
            if (!class_exists( $config[self::CONFIG_CLASS] )) {
                throw new Yadif_Exception( 'Class ' . $config[self::CONFIG_CLASS] . ' not found' );
            }
 
            // check for singleton config parameter and set it to true as default if not found.
            if(!isset($config[self::CONFIG_SCOPE])) {
                $config[self::CONFIG_SCOPE] = self::SCOPE_SINGLETON;
            }
 
            if(!isset($config[self::CONFIG_METHODS])) {
                $config[self::CONFIG_METHODS] = array();
            } elseif(!is_array($config[self::CONFIG_METHODS])) {
                throw new Yadif_Exception("Methods of component '".$name."' are not in array format.");
            } else {
                foreach($config[self::CONFIG_METHODS] AS $k => $method) {
                    if(!isset($method[self::CONFIG_METHOD])) {
                        throw new Yadif_Exception("No method name was set for injection via method.");
                    }
                    if(!isset($method[self::CONFIG_PARAMETERS])) {
                        $method[self::CONFIG_PARAMETERS] = array();
                    }
                    if(!isset($method[self::CONFIG_ARGUMENTS])) {
                        $method[self::CONFIG_ARGUMENTS] = array();
                    } elseif(!is_array($method[self::CONFIG_ARGUMENTS])) {
                        throw new Yadif_Exception("Arguments of method '".$method[self::CONFIG_METHOD]."' in component ".$name." are not given as an array.");
                    }
 
                    $config[self::CONFIG_METHODS][$k] = $method;
                }
            }
 
            $name = strtolower($name);
            $this->_container[$name] = $config;
        } else {
            throw new Yadif_Exception('$string not string|Yadif_Container, is ' . gettype($name));
        }
 
        return $this;
    }
 
    /**
* Bind a parameter
*
* @param string $param The parameter name, to be given with a leading colon ":param"
* @param mixed $value The value to bind to the parameter
* @return Yadif_Container
*/
    public function bindParam($param, $value)
    {
        if (!is_string($param)) {
            throw new Yadif_Exception('$param not string, is ' . gettype($param));
        }
 
        if ($param[0] != ':') {
            throw new Yadif_Exception($param . ' must start with a colon (:)');
        }
 
        $this->_parameters[$param] = $value;
 
        return $this;
    }
 
    /**
* Retrieve a parameter by name
*
* @param mixed $param Retrieve named parameter
* @param string $component
* @param string $method
* @return mixed
*/
    public function getParam($param, $component=null)
    {
        $component = strtolower($component);
        if(isset($this->_container[$component])) {
            $component = $this->_container[$component];
            if(isset($component[self::CONFIG_PARAMETERS][$param])) {
                return $component[self::CONFIG_PARAMETERS][$param];
            }
        }
 
        if(isset($this->_parameters[$param])) {
            return $this->_parameters[$param];
        } else {
            return null;
        }
    }
 
    /**
* Bind multiple parameters by way of array
* @param array $params Array of parameters, key as param to bind, value as the bound value
* @return Yadif_Container
*/
    public function bindParams($params = null)
    {
        if (!is_array($params)) {
            throw new Yadif_Exception('$params must be array, is ' . gettype($params));
        }
 
        foreach ($params as $param => $value) {
            $this->bindParam($param, $value);
        }
 
        return $this;
    }
 
    /**
* Get several components at once.
*
* @param array $components
* @return array
*/
    public function getComponents(array $components)
    {
        foreach ($components as $k =>$value) {
            $components[$k] = $this->getComponent($value);
        }
        return $components;
    }
 
    protected function injectParameters($arguments, $component, array $params=array())
    {
        $injection = array();
        foreach($arguments AS $k => $argument) {
            if(is_array($argument)) {
                $value = $this->injectParameters($argument, $component);
            } elseif(substr($argument, 0, 1) == self::CHAR_CONFIG_VALUE && substr($argument, -1) == self::CHAR_CONFIG_VALUE) {
                $value = $this->getConfigValue($argument);
            } elseif(substr($argument, 0, 1) == self::CHAR_ARGUMENT) {
                if(isset($params[$argument])) {
                    $value = $params[$argument];
                } else {
                    $value = $this->getParam($argument, $component);
                }
            } else {
                $value = $this->getComponent($argument);
            }
            $injection[$k] = $value;
        }
        return $injection;
    }
 
    /**
* Get back a fully assembled component based on the configuration provided beforehand
*
* @param string $name The name of the component
* @return mixed
*/
    public function getComponent($name)
    {
        if (!is_string($name)) {
            return $name;
        }
 
        $origName = $name;
        $name = strtolower($name);
 
        if(isset($this->_instances[$name])) {
            return $this->_instances[$name];
        }
 
        if($name === "thiscontainer") {
            return $this;
        } elseif($name === "clonecontainer") {
            return clone $this;
        } elseif(!array_key_exists($name, $this->_container)) {
            throw new Yadif_Exception("Component '".$origName."' does not exist in container.");
        }
 
        $component = $this->_container[$name];
        $scope = $component[self::CONFIG_SCOPE];
 
        $componentReflection = new ReflectionClass($component[ self::CONFIG_CLASS ]);
 
        $constructorArguments = $component[self::CONFIG_ARGUMENTS];
        $setterMethods = $component[self::CONFIG_METHODS];
 
        if(isset($component[self::CONFIG_FACTORY])) {
            if(!is_callable($component[self::CONFIG_FACTORY])) {
                throw new Yadif_Exception("No valid callback given for the factory method of '".$origName."'.");
            }
            $component = call_user_func_array($component[self::CONFIG_FACTORY], $this->injectParameters($constructorArguments, $name));
        } else if(empty($constructorArguments)) { // if no instructions
                $component = $componentReflection->newInstance();
            } else {
                $component = $componentReflection->newInstanceArgs($this->injectParameters($constructorArguments, $name));
            }
 
        foreach ($setterMethods as $method) {
            $methodName = $method[self::CONFIG_METHOD];
            $params = $method[self::CONFIG_PARAMETERS];
 
            $injection = array();
            if(isset($method[self::CONFIG_ARGUMENTS])) {
                $argsName = $method[self::CONFIG_ARGUMENTS];
                $injection = $this->injectParameters($argsName, null, $params);
            }
 
            if ($componentReflection->getMethod($methodName)->isConstructor()) {
                throw new Yadif_Exception("Cannot use constructor in 'methods' setter injection list. Use 'arguments' key instead.");
            } else {
                call_user_func_array(array($component, $methodName), $injection);
            }
        }
 
        if($scope !== self::SCOPE_PROTOTYPE) {
            $this->_instances[$name] = $component;
        }
 
        return $component;
    }
 
    /**
* Magic Get accesses the {@link getComponent} function and returns the object.
*
* @param string $component
* @throws Yadif_Exception
* @return object
*/
    public function __get($name)
    {
        return $this->getComponent($name);
    }
 
    /**
* Call allows to initiate requests to get[ComponetName] and links against {@link getComponent}.
*
* @param string $method
* @param array $arguments
* @throws Yadif_Exception
* @return object
*/
    public function __call($method, $args)
    {
        if(substr($method, 0, 3) !== "get") {
            throw new Yadif_Exception("Container __call only intercepts get[ComponetName]() like calls.");
        }
        $component = substr($method, 3);
        return $this->getComponent($component);
    }
 
    /**
* Set instance of a name.
*
* @throws Yadif_Exception
* @param string $name
* @param object $instance
*/
    public function __set($name, $instance)
    {
        $origName = $name;
        $name = strtolower($name);
        if(is_object($instance)) {
            $this->_instances[$name] = $instance;
        } else {
            throw new Yadif_Container("Setting instance '".$origName."' with non-object not possible.");
        }
    }
 
    /**
* Is there an instance or a component registered with the given name?
*
* @param string $name
* @return boolean
*/
    public function __isset($name)
    {
        $name = strtolower($name);
        return (
        isset($this->_instances[$name]) ||
            isset($this->_container[$name])
        );
    }
 
    /**
* Given an accessor specification %config.foo.bar% traverse the config and return value.
*
* @param string $accessor
* @return mixed
*/
    protected function getConfigValue($accessor)
    {
        if($this->_config === null) {
            throw new Yadif_Exception("A config value '".$accessor."' is required but no config was given!");
        }
 
        $accessor = substr($accessor, 1, strlen($accessor)-2);
 
        $parts = explode(".", $accessor);
        $current = $this->_config;
        for($i = 0; $i < count($parts); $i++) {
            $current = $current->$parts[$i];
        }
        return $current;
    }
}