1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Lit\Air; |
6
|
|
|
|
7
|
|
|
use Psr\Container\ContainerExceptionInterface; |
8
|
|
|
use Psr\Container\ContainerInterface; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Helper class for resolving stub with container |
12
|
|
|
*/ |
13
|
|
|
class ContainerStub |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @var string |
17
|
|
|
*/ |
18
|
|
|
protected $className; |
19
|
|
|
/** |
20
|
|
|
* @var array |
21
|
|
|
*/ |
22
|
|
|
protected $extraParameters; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* BoltContainerStub constructor. |
26
|
|
|
* |
27
|
|
|
* @param string $className Name of the class. |
28
|
|
|
* @param array $extraParameters Extra params fed into DI factory. |
29
|
|
|
*/ |
30
|
1 |
|
public function __construct(string $className, array $extraParameters = []) |
31
|
|
|
{ |
32
|
1 |
|
$this->className = $className; |
33
|
1 |
|
$this->extraParameters = $extraParameters; |
34
|
1 |
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Shortcut method of constructor. |
38
|
|
|
* |
39
|
|
|
* @param string $className Name of the class. |
40
|
|
|
* @param array $extraParameters Extra params fed into DI factory. |
41
|
|
|
* @return ContainerStub |
42
|
|
|
*/ |
43
|
1 |
|
public static function of(string $className, array $extraParameters = []): self |
44
|
|
|
{ |
45
|
1 |
|
return new static($className, $extraParameters); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* Try to parse the stub |
50
|
|
|
* |
51
|
|
|
* @param mixed $stub The stub. |
52
|
|
|
* @return ContainerStub|null |
53
|
|
|
*/ |
54
|
1 |
|
public static function tryParse($stub): ?self |
55
|
|
|
{ |
56
|
1 |
|
if (is_string($stub) && class_exists($stub)) { |
57
|
|
|
return static::of($stub); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
//[$className, $params] |
61
|
1 |
|
if (is_array($stub) && count($stub) === 2 && class_exists($stub[0])) { |
62
|
1 |
|
return static::of($stub[0], $stub[1]); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return null; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* Populate concrete product from given container |
70
|
|
|
* |
71
|
|
|
* @param ContainerInterface $container The container. |
72
|
|
|
* @param array $extraParameters Extra parameters. |
73
|
|
|
* @return object |
74
|
|
|
* @throws ContainerExceptionInterface Failed to produce. |
75
|
|
|
* @throws \ReflectionException Failed to produce. |
76
|
|
|
*/ |
77
|
1 |
|
public function instantiateFrom(ContainerInterface $container, array $extraParameters = []) |
78
|
|
|
{ |
79
|
1 |
|
return Factory::of($container)->instantiate($this->className, $extraParameters + $this->extraParameters); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|