/
ExtensibleService.php
81 lines (69 loc) · 1.94 KB
/
ExtensibleService.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
<?php
declare(strict_types=1);
namespace Yiisoft\Di;
use Psr\Container\ContainerInterface;
use Yiisoft\Definitions\Contract\DefinitionInterface;
use Yiisoft\Di\Helpers\DefinitionNormalizer;
/**
* @internal A wrapper for a service definition that allows registering extensions.
* An extension is a callable that returns a modified service object:
*
* ```php
* static function (ContainerInterface $container, $service) {
* return $service->withAnotherOption(42);
* }
* ```
*/
final class ExtensibleService implements DefinitionInterface
{
/**
* @var mixed
*/
private $definition;
private string $id;
/**
* @var callable[]
*/
private array $extensions = [];
/**
* @param mixed $definition Definition to allow registering extensions for.
*/
public function __construct($definition, string $id)
{
$this->definition = $definition;
$this->id = $id;
}
/**
* Add an extension.
*
* An extension is a callable that returns a modified service object:
*
* ```php
* static function (ContainerInterface $container, $service) {
* return $service->withAnotherOption(42);
* }
* ```
*
* @param callable $closure An extension to register.
*/
public function addExtension(callable $closure): void
{
$this->extensions[] = $closure;
}
public function resolve(ContainerInterface $container)
{
/** @var mixed $service */
$service = DefinitionNormalizer::normalize($this->definition, $this->id)
->resolve($container);
foreach ($this->extensions as $extension) {
/** @var mixed $result */
$result = $extension($container->get(ContainerInterface::class), $service);
if ($result === null) {
continue;
}
/** @var mixed $service */
$service = $result;
}
return $service;
}
}