Passed
Push — master ( ee03c1...dad2d2 )
by Alexander
02:31
created

ExtensibleService   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
dl 0
loc 41
ccs 12
cts 12
cp 1
rs 10
c 1
b 0
f 0
wmc 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A addExtension() 0 3 1
A resolve() 0 9 2
A __construct() 0 3 1
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 3
    public function __construct($definition)
32
    {
33 3
        $this->definition = $definition;
34 3
    }
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 3
    public function addExtension(callable $closure): void
50
    {
51 3
        $this->extensions[] = $closure;
52 3
    }
53
54 3
    public function resolve(DependencyResolverInterface $container)
55
    {
56 3
        $service = (Normalizer::normalize($this->definition))->resolve($container);
57 3
        $containerInterface = $container->get(ContainerInterface::class);
58 3
        foreach ($this->extensions as $extension) {
59 3
            $service = $extension($containerInterface, $service);
60
        }
61
62 3
        return $service;
63
    }
64
}
65