1
|
|
|
<?php |
2
|
|
|
namespace yii\di\definitions; |
3
|
|
|
|
4
|
|
|
use Psr\Container\ContainerInterface; |
5
|
|
|
use yii\di\contracts\Definition; |
6
|
|
|
use yii\di\exceptions\NotInstantiableException; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Builds object by array config. |
10
|
|
|
* @package yii\di |
11
|
|
|
*/ |
12
|
|
|
class ArrayDefinition implements Definition |
13
|
|
|
{ |
14
|
|
|
private $class; |
15
|
|
|
private $params; |
16
|
|
|
private $config; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @param string $class class name, must not be empty |
20
|
|
|
* @param array $params |
21
|
|
|
* @param array $config |
22
|
|
|
*/ |
23
|
|
|
public function __construct(string $class, array $params = [], array $config = []) |
24
|
|
|
{ |
25
|
|
|
if (empty($class)) { |
26
|
|
|
throw Exception('class name not given'); |
|
|
|
|
27
|
|
|
} |
28
|
|
|
$this->class = $class; |
29
|
|
|
$this->params = $params; |
30
|
|
|
$this->config = $config; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @return string |
35
|
|
|
*/ |
36
|
|
|
public function getClass(): string |
37
|
|
|
{ |
38
|
|
|
return $this->class; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @return array |
43
|
|
|
*/ |
44
|
|
|
public function getParams(): array |
45
|
|
|
{ |
46
|
|
|
return $this->params; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @return array |
51
|
|
|
*/ |
52
|
|
|
public function getConfig(): array |
53
|
|
|
{ |
54
|
|
|
return $this->config; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
private const CLASS_KEY = '__class'; |
58
|
|
|
private const PARAMS_KEY = '__construct()'; |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* @param string $class class name |
62
|
|
|
* @param array $params |
63
|
|
|
* @param array $config |
64
|
|
|
* @return self |
65
|
|
|
*/ |
66
|
|
|
public static function fromArray(string $class = null, array $params = [], array $config = []): self |
67
|
|
|
{ |
68
|
|
|
$class = $config[self::CLASS_KEY] ?? $class; |
69
|
|
|
$params = $config[self::PARAMS_KEY] ?? $params; |
70
|
|
|
|
71
|
|
|
unset($config[self::CLASS_KEY]); |
72
|
|
|
unset($config[self::PARAMS_KEY]); |
73
|
|
|
|
74
|
|
|
if (empty($class)) { |
75
|
|
|
throw new NotInstantiableException(var_export($config, true)); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
return new static($class, $params, $config); |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
public function resolve(ContainerInterface $container, array $params = []) |
82
|
|
|
{ |
83
|
|
|
if (!empty($params)) { |
84
|
|
|
$this->params = array_merge($this->params, $params); |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
return $this->getBuilder()->build($container, $this); |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
private static $builder; |
91
|
|
|
|
92
|
|
|
private function getBuilder() |
93
|
|
|
{ |
94
|
|
|
if (static::$builder === null) { |
|
|
|
|
95
|
|
|
static::$builder = new ArrayBuilder(); |
96
|
|
|
} |
97
|
|
|
|
98
|
|
|
return static::$builder; |
99
|
|
|
} |
100
|
|
|
} |
101
|
|
|
|