Completed
Push — 6.0 ( bcbae5...1124c5 )
by liu
05:09 queued 11s
created

Container::resolving()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
c 2
b 0
f 0
nc 3
nop 2
dl 0
loc 12
ccs 0
cts 7
cp 0
crap 12
rs 10
1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
6
// +----------------------------------------------------------------------
7
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
8
// +----------------------------------------------------------------------
9
// | Author: liu21st <[email protected]>
10
// +----------------------------------------------------------------------
11
declare (strict_types = 1);
12
13
namespace think;
14
15
use ArrayAccess;
16
use ArrayIterator;
17
use Closure;
18
use Countable;
19
use Exception;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, think\Exception. Consider defining an alias.

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...
20
use InvalidArgumentException;
21
use IteratorAggregate;
22
use Psr\Container\ContainerInterface;
23
use ReflectionClass;
24
use ReflectionException;
25
use ReflectionFunction;
26
use ReflectionMethod;
27
use think\exception\ClassNotFoundException;
28
29
/**
30
 * 容器管理类 支持PSR-11
31
 */
32
class Container implements ContainerInterface, ArrayAccess, IteratorAggregate, Countable
33
{
34
    /**
35
     * 容器对象实例
36
     * @var Container|Closure
37
     */
38
    protected static $instance;
39
40
    /**
41
     * 容器中的对象实例
42
     * @var array
43
     */
44
    protected $instances = [];
45
46
    /**
47
     * 容器绑定标识
48
     * @var array
49
     */
50
    protected $bind = [];
51
52
    /**
53
     * 容器回调
54
     * @var array
55
     */
56
    protected $invokeCallback = [];
57
58
    /**
59
     * 获取当前容器的实例(单例)
60
     * @access public
61
     * @return static
62
     */
63 6
    public static function getInstance()
64
    {
65 6
        if (is_null(static::$instance)) {
66 1
            static::$instance = new static;
67
        }
68
69 6
        if (static::$instance instanceof Closure) {
70 1
            return (static::$instance)();
71
        }
72
73 6
        return static::$instance;
74
    }
75
76
    /**
77
     * 设置当前容器的实例
78
     * @access public
79
     * @param object|Closure $instance
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
80
     * @return void
81
     */
82 41
    public static function setInstance($instance): void
83
    {
84 41
        static::$instance = $instance;
85 41
    }
86
87
    /**
88
     * 注册一个容器对象回调
89
     *
90
     * @param  string|Closure $abstract
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
91
     * @param  Closure|null   $callback
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
92
     * @return void
93
     */
94
    public function resolving($abstract, Closure $callback = null): void
95
    {
96
        if ($abstract instanceof Closure) {
97
            $this->invokeCallback['*'][] = $abstract;
98
            return;
99
        }
100
101
        if (isset($this->bind[$abstract])) {
102
            $abstract = $this->bind[$abstract];
103
        }
104
105
        $this->invokeCallback[$abstract][] = $callback;
106
    }
107
108
    /**
109
     * 获取容器中的对象实例 不存在则创建
110
     * @access public
111
     * @param string     $abstract    类名或者标识
112
     * @param array|true $vars        变量
113
     * @param bool       $newInstance 是否每次创建新的实例
114
     * @return object
115
     */
116 1
    public static function pull(string $abstract, array $vars = [], bool $newInstance = false)
117
    {
118 1
        return static::getInstance()->make($abstract, $vars, $newInstance);
119
    }
120
121
    /**
122
     * 获取容器中的对象实例
123
     * @access public
124
     * @param string $abstract 类名或者标识
125
     * @return object
126
     */
127 15
    public function get($abstract)
128
    {
129 15
        if ($this->has($abstract)) {
130 14
            return $this->make($abstract);
131
        }
132
133 1
        throw new ClassNotFoundException('class not exists: ' . $abstract, $abstract);
134
    }
135
136
    /**
137
     * 绑定一个类、闭包、实例、接口实现到容器
138
     * @access public
139
     * @param string|array $abstract 类标识、接口
140
     * @param mixed        $concrete 要绑定的类、闭包或者实例
141
     * @return $this
142
     */
143 9
    public function bind($abstract, $concrete = null)
144
    {
145 9
        if (is_array($abstract)) {
146 4
            $this->bind = array_merge($this->bind, $abstract);
147 6
        } elseif ($concrete instanceof Closure) {
148 3
            $this->bind[$abstract] = $concrete;
149 4
        } elseif (is_object($concrete)) {
150 3
            $this->instance($abstract, $concrete);
151
        } else {
152 2
            $this->bind[$abstract] = $concrete;
153
        }
154
155 9
        return $this;
156
    }
157
158
    /**
159
     * 绑定一个类实例到容器
160
     * @access public
161
     * @param string $abstract 类名或者标识
162
     * @param object $instance 类的实例
163
     * @return $this
164
     */
165 22
    public function instance(string $abstract, $instance)
166
    {
167 22
        if (isset($this->bind[$abstract])) {
168 19
            $bind = $this->bind[$abstract];
169
170 19
            if (is_string($bind)) {
171 19
                return $this->instance($bind, $instance);
172
            }
173
        }
174
175 22
        $this->instances[$abstract] = $instance;
176
177 22
        return $this;
178
    }
179
180
    /**
181
     * 判断容器中是否存在类及标识
182
     * @access public
183
     * @param string $abstract 类名或者标识
184
     * @return bool
185
     */
186 15
    public function bound(string $abstract): bool
187
    {
188 15
        return isset($this->bind[$abstract]) || isset($this->instances[$abstract]);
189
    }
190
191
    /**
192
     * 判断容器中是否存在类及标识
193
     * @access public
194
     * @param string $name 类名或者标识
195
     * @return bool
196
     */
197 15
    public function has($name): bool
198
    {
199 15
        return $this->bound($name);
200
    }
201
202
    /**
203
     * 判断容器中是否存在对象实例
204
     * @access public
205
     * @param string $abstract 类名或者标识
206
     * @return bool
207
     */
208 4
    public function exists(string $abstract): bool
209
    {
210 4
        if (isset($this->bind[$abstract])) {
211 3
            $bind = $this->bind[$abstract];
212
213 3
            if (is_string($bind)) {
214 2
                return $this->exists($bind);
215
            }
216
        }
217
218 4
        return isset($this->instances[$abstract]);
219
    }
220
221
    /**
222
     * 创建类的实例 已经存在则直接获取
223
     * @access public
224
     * @param string $abstract    类名或者标识
225
     * @param array  $vars        变量
226
     * @param bool   $newInstance 是否每次创建新的实例
227
     * @return mixed
228
     */
229 19
    public function make(string $abstract, array $vars = [], bool $newInstance = false)
230
    {
231 19
        if (isset($this->instances[$abstract]) && !$newInstance) {
232 13
            return $this->instances[$abstract];
233
        }
234
235 18
        if (isset($this->bind[$abstract])) {
236 16
            $concrete = $this->bind[$abstract];
237
238 16
            if ($concrete instanceof Closure) {
239 3
                $object = $this->invokeFunction($concrete, $vars);
240
            } else {
241 16
                return $this->make($concrete, $vars, $newInstance);
242
            }
243
        } else {
244 15
            $object = $this->invokeClass($abstract, $vars);
245
        }
246
247 18
        if (!$newInstance) {
248 18
            $this->instances[$abstract] = $object;
249
        }
250
251 18
        return $object;
252
    }
253
254
    /**
255
     * 删除容器中的对象实例
256
     * @access public
257
     * @param string $name 类名或者标识
258
     * @return void
259
     */
260 2
    public function delete($name)
261
    {
262 2
        if (isset($this->bind[$name])) {
263 2
            $bind = $this->bind[$name];
264
265 2
            if (is_string($bind)) {
266 2
                return $this->delete($bind);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->delete($bind) targeting think\Container::delete() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
267
            }
268
        }
269
270 2
        if (isset($this->instances[$name])) {
271 2
            unset($this->instances[$name]);
272
        }
273 2
    }
274
275
    /**
276
     * 执行函数或者闭包方法 支持参数调用
277
     * @access public
278
     * @param mixed $function 函数或者闭包
279
     * @param array $vars     参数
280
     * @return mixed
281
     */
282 5
    public function invokeFunction($function, array $vars = [])
283
    {
284
        try {
285 5
            $reflect = new ReflectionFunction($function);
286
287 4
            $args = $this->bindParams($reflect, $vars);
288
289 4
            return call_user_func_array($function, $args);
290 1
        } catch (ReflectionException $e) {
291 1
            throw new Exception('function not exists: ' . $function . '()');
292
        }
293
    }
294
295
    /**
296
     * 调用反射执行类的方法 支持参数绑定
297
     * @access public
298
     * @param mixed $method 方法
299
     * @param array $vars   参数
300
     * @return mixed
301
     */
302 3
    public function invokeMethod($method, array $vars = [])
303
    {
304
        try {
305 3
            if (is_array($method)) {
306 3
                $class   = is_object($method[0]) ? $method[0] : $this->invokeClass($method[0]);
307 3
                $reflect = new ReflectionMethod($class, $method[1]);
308
            } else {
309
                // 静态方法
310 1
                $reflect = new ReflectionMethod($method);
0 ignored issues
show
Bug introduced by
The call to ReflectionMethod::__construct() has too few arguments starting with name. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

310
                $reflect = /** @scrutinizer ignore-call */ new ReflectionMethod($method);

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
311
            }
312
313 2
            $args = $this->bindParams($reflect, $vars);
314
315 2
            return $reflect->invokeArgs($class ?? null, $args);
316 1
        } catch (ReflectionException $e) {
317 1
            if (is_array($method)) {
318 1
                $class    = is_object($method[0]) ? get_class($method[0]) : $method[0];
0 ignored issues
show
introduced by
The condition is_object($method[0]) is always false.
Loading history...
319 1
                $callback = $class . '::' . $method[1];
320
            } else {
321
                $callback = $method;
322
            }
323
324 1
            throw new Exception('method not exists: ' . $callback . '()');
325
        }
326
    }
327
328
    /**
329
     * 调用反射执行类的方法 支持参数绑定
330
     * @access public
331
     * @param object $instance 对象实例
332
     * @param mixed  $reflect  反射类
333
     * @param array  $vars     参数
334
     * @return mixed
335
     */
336 1
    public function invokeReflectMethod($instance, $reflect, array $vars = [])
337
    {
338 1
        $args = $this->bindParams($reflect, $vars);
339
340 1
        return $reflect->invokeArgs($instance, $args);
341
    }
342
343
    /**
344
     * 调用反射执行callable 支持参数绑定
345
     * @access public
346
     * @param mixed $callable
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
347
     * @param array $vars 参数
0 ignored issues
show
Coding Style introduced by
Expected 5 spaces after parameter name; 1 found
Loading history...
348
     * @return mixed
349
     */
350 2
    public function invoke($callable, array $vars = [])
351
    {
352 2
        if ($callable instanceof Closure) {
353 1
            return $this->invokeFunction($callable, $vars);
354
        }
355
356 2
        return $this->invokeMethod($callable, $vars);
357
    }
358
359
    /**
360
     * 调用反射执行类的实例化 支持依赖注入
361
     * @access public
362
     * @param string $class 类名
363
     * @param array  $vars  参数
364
     * @return mixed
365
     */
366 24
    public function invokeClass(string $class, array $vars = [])
367
    {
368
        try {
369 24
            $reflect = new ReflectionClass($class);
370
371 23
            if ($reflect->hasMethod('__make')) {
372 11
                $method = new ReflectionMethod($class, '__make');
373
374 11
                if ($method->isPublic() && $method->isStatic()) {
375 11
                    $args = $this->bindParams($method, $vars);
376 11
                    return $method->invokeArgs(null, $args);
377
                }
378
            }
379
380 20
            $constructor = $reflect->getConstructor();
381
382 20
            $args = $constructor ? $this->bindParams($constructor, $vars) : [];
0 ignored issues
show
introduced by
$constructor is of type ReflectionMethod, thus it always evaluated to true.
Loading history...
383
384 20
            $object = $reflect->newInstanceArgs($args);
385
386 20
            $this->invokeAfter($class, $object);
387
388 20
            return $object;
389 1
        } catch (ReflectionException $e) {
390 1
            throw new ClassNotFoundException('class not exists: ' . $class, $class);
391
        }
392
    }
393
394
    /**
395
     * 执行invokeClass回调
396
     * @access protected
397
     * @param string $class  对象类名
398
     * @param object $object 容器对象实例
399
     * @return void
400
     */
401 20
    protected function invokeAfter(string $class, $object): void
402
    {
403 20
        if (isset($this->invokeCallback['*'])) {
404
            foreach ($this->invokeCallback['*'] as $callback) {
405
                $callback($object, $this);
406
            }
407
        }
408
409 20
        if (isset($this->invokeCallback[$class])) {
410
            foreach ($this->invokeCallback[$class] as $callback) {
411
                $callback($object, $this);
412
            }
413
        }
414 20
    }
415
416
    /**
417
     * 绑定参数
418
     * @access protected
419
     * @param \ReflectionMethod|\ReflectionFunction $reflect 反射类
420
     * @param array                                 $vars    参数
421
     * @return array
422
     */
423 26
    protected function bindParams($reflect, array $vars = []): array
424
    {
425 26
        if ($reflect->getNumberOfParameters() == 0) {
426 14
            return [];
427
        }
428
429
        // 判断数组类型 数字数组时按顺序绑定参数
430 20
        reset($vars);
431 20
        $type   = key($vars) === 0 ? 1 : 0;
432 20
        $params = $reflect->getParameters();
433 20
        $args   = [];
434
435 20
        foreach ($params as $param) {
436 20
            $name      = $param->getName();
437 20
            $lowerName = self::parseName($name);
438 20
            $class     = $param->getClass();
439
440 20
            if ($class) {
441 19
                $args[] = $this->getObjectParam($class->getName(), $vars);
442 18
            } elseif (1 == $type && !empty($vars)) {
443 10
                $args[] = array_shift($vars);
444 9
            } elseif (0 == $type && isset($vars[$name])) {
445 1
                $args[] = $vars[$name];
446 9
            } elseif (0 == $type && isset($vars[$lowerName])) {
447 1
                $args[] = $vars[$lowerName];
448 9
            } elseif ($param->isDefaultValueAvailable()) {
449 9
                $args[] = $param->getDefaultValue();
450
            } else {
451 20
                throw new InvalidArgumentException('method param miss:' . $name);
452
            }
453
        }
454
455 20
        return $args;
456
    }
457
458
    /**
459
     * 字符串命名风格转换
460
     * type 0 将Java风格转换为C的风格 1 将C风格转换为Java的风格
461
     * @access public
462
     * @param string  $name    字符串
463
     * @param integer $type    转换类型
464
     * @param bool    $ucfirst 首字母是否大写(驼峰规则)
465
     * @return string
466
     */
467 21
    public static function parseName(string $name = null, int $type = 0, bool $ucfirst = true): string
468
    {
469 21
        if ($type) {
470
            $name = preg_replace_callback('/_([a-zA-Z])/', function ($match) {
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
471 1
                return strtoupper($match[1]);
472 1
            }, $name);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
473 1
            return $ucfirst ? ucfirst($name) : lcfirst($name);
474
        }
475
476 21
        return strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_"));
477
    }
478
479
    /**
480
     * 获取类名(不包含命名空间)
481
     * @access public
482
     * @param string|object $class
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
483
     * @return string
484
     */
485 1
    public static function classBaseName($class): string
486
    {
487 1
        $class = is_object($class) ? get_class($class) : $class;
488 1
        return basename(str_replace('\\', '/', $class));
489
    }
490
491
    /**
0 ignored issues
show
Coding Style introduced by
Parameter ...$args should have a doc-comment as per coding-style.
Loading history...
492
     * 创建工厂对象实例
493
     * @access public
494
     * @param string $name      工厂类名
495
     * @param string $namespace 默认命名空间
496
     * @param array  $args
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Doc comment for parameter $args does not match actual variable name ...$args
Loading history...
497
     * @return mixed
498
     */
499 4
    public static function factory(string $name, string $namespace = '', ...$args)
500
    {
501 4
        $class = false !== strpos($name, '\\') ? $name : $namespace . ucwords($name);
502
503 4
        if (class_exists($class)) {
504 4
            return Container::getInstance()->invokeClass($class, $args);
505
        }
506
507 1
        throw new ClassNotFoundException('class not exists:' . $class, $class);
508
    }
509
510
    /**
511
     * 获取对象类型的参数值
512
     * @access protected
513
     * @param string $className 类名
514
     * @param array  $vars      参数
515
     * @return mixed
516
     */
517 19
    protected function getObjectParam(string $className, array &$vars)
518
    {
519 19
        $array = $vars;
520 19
        $value = array_shift($array);
521
522 19
        if ($value instanceof $className) {
523 1
            $result = $value;
524 1
            array_shift($vars);
525
        } else {
526 19
            $result = $this->make($className);
527
        }
528
529 19
        return $result;
530
    }
531
532 1
    public function __set($name, $value)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __set()
Loading history...
533
    {
534 1
        $this->bind($name, $value);
535 1
    }
536
537 22
    public function __get($name)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __get()
Loading history...
538
    {
539 22
        return $this->get($name);
540
    }
541
542 1
    public function __isset($name): bool
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __isset()
Loading history...
543
    {
544 1
        return $this->exists($name);
545
    }
546
547 2
    public function __unset($name)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __unset()
Loading history...
548
    {
549 2
        $this->delete($name);
550 2
    }
551
552 1
    public function offsetExists($key)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function offsetExists()
Loading history...
553
    {
554 1
        return $this->exists($key);
555
    }
556
557 1
    public function offsetGet($key)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function offsetGet()
Loading history...
558
    {
559 1
        return $this->make($key);
560
    }
561
562 1
    public function offsetSet($key, $value)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function offsetSet()
Loading history...
563
    {
564 1
        $this->bind($key, $value);
565 1
    }
566
567 1
    public function offsetUnset($key)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function offsetUnset()
Loading history...
568
    {
569 1
        $this->delete($key);
570 1
    }
571
572
    //Countable
573
    public function count()
0 ignored issues
show
Coding Style introduced by
You must use "/**" style comments for a function comment
Loading history...
574
    {
575
        return count($this->instances);
576
    }
577
578
    //IteratorAggregate
579 1
    public function getIterator()
0 ignored issues
show
Coding Style introduced by
You must use "/**" style comments for a function comment
Loading history...
580
    {
581 1
        return new ArrayIterator($this->instances);
582
    }
583
}
584