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