Completed
Push — 2.1 ( b04e0e...d1ff65 )
by
unknown
21:06
created

Instance::ensure()   C

Complexity

Conditions 16
Paths 28

Size

Total Lines 49
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 27
CRAP Score 16.256

Importance

Changes 0
Metric Value
dl 0
loc 49
ccs 27
cts 30
cp 0.9
rs 5.1186
c 0
b 0
f 0
cc 16
eloc 31
nc 28
nop 3
crap 16.256

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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::class,
30
 *     'db' => Instance::of('db')
31
 * ]);
32
 * $container->set('db', [
33
 *     '__class' => \yii\db\Connection::class,
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::class);
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 460
    protected function __construct($id)
69
    {
70 460
        $this->id = $id;
71 460
    }
72
73
    /**
74
     * Creates a new Instance object.
75
     * @param string $id the component ID
76
     * @return Instance the new Instance object.
77
     */
78 113
    public static function of($id)
79
    {
80 113
        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::class);
98
     * // returns an instance of Connection using the given configuration
99
     * $db = Instance::ensure(['dsn' => 'sqlite:path/to/my.db'], Connection::class);
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 783
    public static function ensure($reference, $type = null, $container = null)
112
    {
113 783
        if (is_array($reference)) {
114 559
            $class = $type;
115 559
            if (isset($reference['__class'])) {
116 559
                $class = $reference['__class'];
117 559
                unset($reference['__class']);
118
            }
119 559
            if (isset($reference['class'])) {
120
                // @todo remove fallback
121
                $class = $reference['class'];
122
                unset($reference['class']);
123
            }
124
125 559
            if (!$container instanceof Container) {
126 557
                $container = Yii::$container;
127
            }
128 559
            $component = $container->get($class, [], $reference);
129 559
            if ($type === null || $component instanceof $type) {
130 558
                return $component;
131
            }
132
133 1
            throw new InvalidConfigException('Invalid data type: ' . $class . '. ' . $type . ' is expected.');
134
        } elseif (empty($reference)) {
135 1
            throw new InvalidConfigException('The required component is not specified.');
136
        }
137
138 547
        if (is_string($reference)) {
139 359
            $reference = new static($reference);
140 476
        } elseif ($type === null || $reference instanceof $type) {
141 474
            return $reference;
142
        }
143
144 361
        if ($reference instanceof self) {
145
            try {
146 360
                $component = $reference->get($container);
147 3
            } catch (\ReflectionException $e) {
148 3
                throw new InvalidConfigException('Failed to instantiate component or class "' . $reference->id . '".', 0, $e);
149
            }
150 358
            if ($type === null || $component instanceof $type) {
151 357
                return $component;
152
            }
153
154 1
            throw new InvalidConfigException('"' . $reference->id . '" refers to a ' . get_class($component) . " component. $type is expected.");
155
        }
156
157 1
        $valueType = is_object($reference) ? get_class($reference) : gettype($reference);
158 1
        throw new InvalidConfigException("Invalid data type: $valueType. $type is expected.");
159
    }
160
161
    /**
162
     * Returns the actual object referenced by this Instance object.
163
     * @param ServiceLocator|Container $container the container used to locate the referenced object.
164
     * If null, the method will first try `Yii::$app` then `Yii::$container`.
165
     * @return object the actual object referenced by this Instance object.
166
     */
167 361
    public function get($container = null)
168
    {
169 361
        if ($container) {
170 6
            return $container->get($this->id);
171
        }
172 355
        if (Yii::$app && Yii::$app->has($this->id)) {
173 85
            return Yii::$app->get($this->id);
174
        }
175
176 282
        return Yii::$container->get($this->id);
177
    }
178
179
    /**
180
     * Restores class state after using `var_export()`.
181
     *
182
     * @param array $state
183
     * @return Instance
184
     * @throws InvalidConfigException when $state property does not contain `id` parameter
185
     * @see var_export()
186
     * @since 2.0.12
187
     */
188 2
    public static function __set_state($state)
189
    {
190 2
        if (!isset($state['id'])) {
191 1
            throw new InvalidConfigException('Failed to instantiate class "Instance". Required parameter "id" is missing');
192
        }
193
194 1
        return new self($state['id']);
195
    }
196
}
197