1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Antidot\Container; |
6
|
|
|
|
7
|
|
|
use Psr\Container\ContainerInterface; |
8
|
|
|
use function array_reduce; |
9
|
|
|
use function is_callable; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* @deprecated will remove in version 1.0.0 |
13
|
|
|
* |
14
|
|
|
* Aura.Di-compatible delegator factory. |
15
|
|
|
* |
16
|
|
|
* Map an instance of this: |
17
|
|
|
* |
18
|
|
|
* <code> |
19
|
|
|
* $container->set( |
20
|
|
|
* $serviceName, |
21
|
|
|
* $container->lazyGetCall( |
22
|
|
|
* $delegatorFactoryInstance, |
23
|
|
|
* 'build', |
24
|
|
|
* $container, |
25
|
|
|
* $serviceName |
26
|
|
|
* ) |
27
|
|
|
* ) |
28
|
|
|
* </code> |
29
|
|
|
* |
30
|
|
|
* Instances receive the list of delegator factory names or instances, and a |
31
|
|
|
* closure that can create the initial service instance to pass to the first |
32
|
|
|
* delegator. |
33
|
|
|
*/ |
34
|
|
|
final class ContainerDelegatorFactory |
35
|
|
|
{ |
36
|
|
|
/** |
37
|
|
|
* @var array Either delegator factory names or instances. |
38
|
|
|
*/ |
39
|
|
|
private $delegators; |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @var callable |
43
|
|
|
*/ |
44
|
|
|
private $factory; |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @param array $delegators Array of delegator factory names or instances. |
48
|
|
|
* @param callable $factory Callable that can return the initial instance. |
49
|
|
|
*/ |
50
|
|
|
public function __construct(array $delegators, callable $factory) |
51
|
|
|
{ |
52
|
|
|
$this->delegators = $delegators; |
53
|
|
|
$this->factory = $factory; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* Build the instance, invoking each delegator with the result of the previous. |
58
|
|
|
* |
59
|
|
|
* @param ContainerInterface $container |
60
|
|
|
* @param string $serviceName |
61
|
|
|
* @return mixed |
62
|
|
|
*/ |
63
|
|
|
public function __invoke(ContainerInterface $container, $serviceName) |
64
|
|
|
{ |
65
|
|
|
$factory = $this->factory; |
66
|
|
|
|
67
|
|
|
return array_reduce( |
68
|
|
|
$this->delegators, |
69
|
|
|
static function ($instance, $delegatorName) use ($serviceName, $container) { |
70
|
|
|
$delegator = is_callable($delegatorName) ? $delegatorName : new $delegatorName(); |
71
|
|
|
|
72
|
|
|
return $delegator($container, $serviceName, static function () use ($instance) { |
73
|
|
|
return $instance; |
74
|
|
|
}); |
75
|
|
|
}, |
76
|
|
|
$factory() |
77
|
|
|
); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|