ExtensibleService::addExtension()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 1
b 0
f 0
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 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 callable[]
25
     */
26
    private array $extensions = [];
27
28
    /**
29
     * @param mixed $definition Definition to allow registering extensions for.
30
     */
31 8
    public function __construct(
32
        private mixed $definition,
33
        private string $id
34
    ) {
35 8
    }
36
37
    /**
38
     * Add an extension.
39
     *
40
     * An extension is callable that returns a modified service object:
41
     *
42
     * ```php
43
     * static function (ContainerInterface $container, $service) {
44
     *     return $service->withAnotherOption(42);
45
     * }
46
     * ```
47
     *
48
     * @param callable $closure An extension to register.
49
     */
50 7
    public function addExtension(callable $closure): void
51
    {
52 7
        $this->extensions[] = $closure;
53
    }
54
55 6
    public function resolve(ContainerInterface $container): mixed
56
    {
57
        /** @var mixed $service */
58 6
        $service = DefinitionNormalizer::normalize($this->definition, $this->id)
59 6
            ->resolve($container);
60
61 6
        foreach ($this->extensions as $extension) {
62
            /** @var mixed $result */
63 6
            $result = $extension($container->get(ContainerInterface::class), $service);
64 6
            if ($result === null) {
65 1
                continue;
66
            }
67
68
            /** @var mixed $service */
69 6
            $service = $result;
70
        }
71
72 6
        return $service;
73
    }
74
}
75