1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Di; |
6
|
|
|
|
7
|
|
|
use Psr\Container\ContainerInterface; |
8
|
|
|
use Yiisoft\Definitions\Contract\DefinitionInterface; |
9
|
|
|
use Yiisoft\Di\Helpers\DefinitionNormalizer; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* @internal A wrapper for a service definition that allows registering extensions. |
13
|
|
|
* An extension is a callable that returns a modified service object: |
14
|
|
|
* |
15
|
|
|
* ```php |
16
|
|
|
* static function (ContainerInterface $container, $service) { |
17
|
|
|
* return $service->withAnotherOption(42); |
18
|
|
|
* } |
19
|
|
|
* ``` |
20
|
|
|
*/ |
21
|
|
|
final class ExtensibleService implements DefinitionInterface |
22
|
|
|
{ |
23
|
|
|
/** |
24
|
|
|
* @var mixed |
25
|
|
|
*/ |
26
|
|
|
private $definition; |
27
|
|
|
|
28
|
|
|
private string $id; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @var callable[] |
32
|
|
|
*/ |
33
|
|
|
private array $extensions = []; |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @param mixed $definition Definition to allow registering extensions for. |
37
|
|
|
*/ |
38
|
8 |
|
public function __construct($definition, string $id) |
39
|
|
|
{ |
40
|
8 |
|
$this->definition = $definition; |
41
|
8 |
|
$this->id = $id; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* Add an extension. |
46
|
|
|
* |
47
|
|
|
* An extension is a callable that returns a modified service object: |
48
|
|
|
* |
49
|
|
|
* ```php |
50
|
|
|
* static function (ContainerInterface $container, $service) { |
51
|
|
|
* return $service->withAnotherOption(42); |
52
|
|
|
* } |
53
|
|
|
* ``` |
54
|
|
|
* |
55
|
|
|
* @param callable $closure An extension to register. |
56
|
|
|
*/ |
57
|
7 |
|
public function addExtension(callable $closure): void |
58
|
|
|
{ |
59
|
7 |
|
$this->extensions[] = $closure; |
60
|
|
|
} |
61
|
|
|
|
62
|
6 |
|
public function resolve(ContainerInterface $container) |
63
|
|
|
{ |
64
|
|
|
/** @var mixed $service */ |
65
|
6 |
|
$service = DefinitionNormalizer::normalize($this->definition, $this->id) |
66
|
6 |
|
->resolve($container); |
67
|
|
|
|
68
|
6 |
|
foreach ($this->extensions as $extension) { |
69
|
|
|
/** @var mixed $result */ |
70
|
6 |
|
$result = $extension($container->get(ContainerInterface::class), $service); |
71
|
6 |
|
if ($result === null) { |
72
|
1 |
|
continue; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** @var mixed $service */ |
76
|
6 |
|
$service = $result; |
77
|
|
|
} |
78
|
|
|
|
79
|
6 |
|
return $service; |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|