Test Failed
Push — lazy-services ( 4bdd4b...592c23 )
by Dmitriy
02:36
created

ExtensibleService::addExtension()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
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\DependencyResolverInterface;
10
11
/**
12
 * 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
    private DefinitionInterface $definition;
24
    private array $extensions = [];
25
26
    /**
27
     * @param DefinitionInterface $definition Definition to allow registering extensions for.
28
     */
29
    public function __construct(DefinitionInterface $definition)
30
    {
31
        $this->definition = $definition;
32
    }
33
34
    /**
35
     * Add an extension.
36
     *
37
     * An extension is a callable that returns a modified service object:
38
     *
39
     * ```php
40
     * static function (ContainerInterface $container, $service) {
41
     *     return $service->withAnotherOption(42);
42
     * }
43
     * ```
44
     *
45
     * @param callable $closure An extension to register.
46
     */
47
    public function addExtension(callable $closure): void
48
    {
49
        $this->extensions[] = $closure;
50
    }
51
52
    public function resolve(DependencyResolverInterface $container)
53
    {
54
        $service = $this->definition->resolve($container);
55
        $containerInterface = $container->get(ContainerInterface::class);
56
        foreach ($this->extensions as $extension) {
57
            $service = $extension($containerInterface, $service);
58
        }
59
60
        return $service;
61
    }
62
}
63