Passed
Push — master ( 86fa88...ed1da9 )
by teng
01:20
created

ContainerAwareTrait   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
dl 0
loc 50
rs 10
c 1
b 0
f 0
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A setContainer() 0 3 1
A __get() 0 17 4
1
<?php
2
/**
3
 * @copyright (C) 2019 pokerapp.cn
4
 * @license   https://pokerapp.cn/license
5
 */
6
namespace poker\container\traits;
7
8
use RuntimeException;
9
use poker\container\Container;
10
11
use function vsprintf;
12
13
/**
14
 * 容器识别trait
15
 *
16
 * @author Levine <[email protected]>
17
 *
18
 * @property \poker\application\AbstractApplication $app
19
 */
20
trait ContainerAwareTrait
21
{
22
	/**
23
	 * 容器实例
24
	 *
25
	 * @var \poker\container\Container
26
	 */
27
	protected $container;
28
29
	/**
30
	 * 已解析对象的数组或对已解析对象的引用
31
	 *
32
	 * @var array
33
	 */
34
	protected $resolved = [];
35
36
	/**
37
	 * 设置容器实例
38
	 *
39
	 * @param \poker\container\Container $container 容器实例
40
	 */
41
	public function setContainer(Container $container): void
42
	{
43
		$this->container = $container;
44
	}
45
46
	/**
47
	 * 使用魔术方法从容器中解析项目
48
	 *
49
	 * @param  string            $key
50
	 * @throws \RuntimeException
51
	 * @return mixed
52
	 */
53
	public function __get(string $key)
54
	{
55
		if (isset($this->resolved[$key])) {
56
			return $this->resolved[$key];
57
		}
58
59
		if ($this->container->has($key) === false) {
60
			throw new RuntimeException(vsprintf('Unable to resolve [ %s ].', [$key]));
61
		}
62
63
		$resolved = $this->container->get($key);
64
65
		if ($this->container->isSingleton($key) === false) {
66
			return $resolved;
67
		}
68
69
		return $this->resolved[$key] = $resolved;
70
	}
71
}
72