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