Completed
Push — master ( bfa239...5e422f )
by Dmitry
14:56
created

Instance::get()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.2
c 0
b 0
f 0
ccs 6
cts 6
cp 1
cc 4
eloc 7
nc 3
nop 1
crap 4
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\di;
9
10
use Yii;
11
use yii\base\InvalidConfigException;
12
13
/**
14
 * Instance represents a reference to a named object in a dependency injection (DI) container or a service locator.
15
 *
16
 * You may use [[get()]] to obtain the actual object referenced by [[id]].
17
 *
18
 * Instance is mainly used in two places:
19
 *
20
 * - When configuring a dependency injection container, you use Instance to reference a class name, interface name
21
 *   or alias name. The reference can later be resolved into the actual object by the container.
22
 * - In classes which use service locator to obtain dependent objects.
23
 *
24
 * The following example shows how to configure a DI container with Instance:
25
 *
26
 * ```php
27
 * $container = new \yii\di\Container;
28
 * $container->set('cache', [
29
 *     'class' => 'yii\caching\DbCache',
30
 *     'db' => Instance::of('db')
31
 * ]);
32
 * $container->set('db', [
33
 *     'class' => 'yii\db\Connection',
34
 *     'dsn' => 'sqlite:path/to/file.db',
35
 * ]);
36
 * ```
37
 *
38
 * And the following example shows how a class retrieves a component from a service locator:
39
 *
40
 * ```php
41
 * class DbCache extends Cache
42
 * {
43
 *     public $db = 'db';
44
 *
45
 *     public function init()
46
 *     {
47
 *         parent::init();
48
 *         $this->db = Instance::ensure($this->db, 'yii\db\Connection');
49
 *     }
50
 * }
51
 * ```
52
 *
53
 * @author Qiang Xue <[email protected]>
54
 * @since 2.0
55
 */
56
class Instance
57
{
58
    /**
59
     * @var string the component ID, class name, interface name or alias name
60
     */
61
    public $id;
62
63
64
    /**
65
     * Constructor.
66
     * @param string $id the component ID
67
     */
68 60
    protected function __construct($id)
69
    {
70 60
        $this->id = $id;
71 60
    }
72
73
    /**
74
     * Creates a new Instance object.
75
     * @param string $id the component ID
76
     * @return Instance the new Instance object.
77
     */
78 20
    public static function of($id)
79
    {
80 20
        return new static($id);
81
    }
82
83
    /**
84
     * Resolves the specified reference into the actual object and makes sure it is of the specified type.
85
     *
86
     * The reference may be specified as a string or an Instance object. If the former,
87
     * it will be treated as a component ID, a class/interface name or an alias, depending on the container type.
88
     *
89
     * If you do not specify a container, the method will first try `Yii::$app` followed by `Yii::$container`.
90
     *
91
     * For example,
92
     *
93
     * ```php
94
     * use yii\db\Connection;
95
     *
96
     * // returns Yii::$app->db
97
     * $db = Instance::ensure('db', Connection::className());
98
     * // returns an instance of Connection using the given configuration
99
     * $db = Instance::ensure(['dsn' => 'sqlite:path/to/my.db'], Connection::className());
100
     * ```
101
     *
102
     * @param object|string|array|static $reference an object or a reference to the desired object.
103
     * You may specify a reference in terms of a component ID or an Instance object.
104
     * Starting from version 2.0.2, you may also pass in a configuration array for creating the object.
105
     * If the "class" value is not specified in the configuration array, it will use the value of `$type`.
106
     * @param string $type the class/interface name to be checked. If null, type check will not be performed.
107
     * @param ServiceLocator|Container $container the container. This will be passed to [[get()]].
108
     * @return object the object referenced by the Instance, or `$reference` itself if it is an object.
109
     * @throws InvalidConfigException if the reference is invalid
110
     */
111 189
    public static function ensure($reference, $type = null, $container = null)
112
    {
113 189
        if (is_array($reference)) {
114 3
            $class = isset($reference['class']) ? $reference['class'] : $type;
115 3
            if (!$container instanceof Container) {
116 1
                $container = Yii::$container;
117 1
            }
118 3
            unset($reference['class']);
119 3
            return $container->get($class, [], $reference);
120 189
        } elseif (empty($reference)) {
121 1
            throw new InvalidConfigException('The required component is not specified.');
122
        }
123
124 188
        if (is_string($reference)) {
125 40
            $reference = new static($reference);
126 188
        } elseif ($type === null || $reference instanceof $type) {
127 164
            return $reference;
128
        }
129
130 43
        if ($reference instanceof self) {
131
            try {
132 42
                $component = $reference->get($container);
133 42
            } catch(\ReflectionException $e) {
134 3
                throw new InvalidConfigException('Failed to instantiate component or class "' . $reference->id . '".', 0, $e);
135
            }
136 39
            if ($type === null || $component instanceof $type) {
137 38
                return $component;
138
            } else {
139 1
                throw new InvalidConfigException('"' . $reference->id . '" refers to a ' . get_class($component) . " component. $type is expected.");
140
            }
141
        }
142
143 1
        $valueType = is_object($reference) ? get_class($reference) : gettype($reference);
144 1
        throw new InvalidConfigException("Invalid data type: $valueType. $type is expected.");
145
    }
146
147
    /**
148
     * Returns the actual object referenced by this Instance object.
149
     * @param ServiceLocator|Container $container the container used to locate the referenced object.
150
     * If null, the method will first try `Yii::$app` then `Yii::$container`.
151
     * @return object the actual object referenced by this Instance object.
152
     */
153 43
    public function get($container = null)
154
    {
155 43
        if ($container) {
156 6
            return $container->get($this->id);
157
        }
158 37
        if (Yii::$app && Yii::$app->has($this->id)) {
159 33
            return Yii::$app->get($this->id);
160
        } else {
161 4
            return Yii::$container->get($this->id);
162
        }
163
    }
164
165
    /**
166
     * Restores class state after using `var_export()`
167
     *
168
     * @param array $state
169
     * @return Instance
170
     * @throws InvalidConfigException when $state property does not contain `id` parameter
171
     * @see var_export()
172
     * @since 2.0.12
173
     */
174 2
    public static function __set_state($state)
175
    {
176 2
        if (!isset($state['id'])) {
177 1
            throw new InvalidConfigException('Failed to instantiate class "Instance". Required parameter "id" is missing');
178
        }
179
180 1
        return new self($state['id']);
181
    }
182
}
183