DynamicReference::to()   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
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Definitions;
6
7
use Psr\Container\ContainerInterface;
8
use Yiisoft\Definitions\Contract\DefinitionInterface;
9
use Yiisoft\Definitions\Contract\ReferenceInterface;
10
use Yiisoft\Definitions\Exception\InvalidConfigException;
11
use Yiisoft\Definitions\Helpers\Normalizer;
12
13
use function is_callable;
14
use function is_object;
15
16
/**
17
 * The `DynamicReference` defines a dependency to a service not defined in the container.
18
 * Definition may be defined multiple ways ({@see Normalizer}). For example:
19
 *
20
 * ```php
21
 * [
22
 *    MyService::class => [
23
 *        '__construct()' => [
24
 *            DynamicReference::to([
25
 *                'class' => SomeClass::class,
26
 *                '$someProp' => 15
27
 *            ])
28
 *        ]
29
 *    ]
30
 * ]
31
 * ```
32
 */
33
final class DynamicReference implements ReferenceInterface
34
{
35
    private DefinitionInterface $definition;
36
37
    /**
38
     * @throws InvalidConfigException
39
     */
40 8
    private function __construct(mixed $definition)
41
    {
42 8
        if (is_object($definition) && !is_callable($definition)) {
43 1
            throw new InvalidConfigException('DynamicReference don\'t support object as definition.');
44
        }
45
46 7
        $this->definition = Normalizer::normalize($definition);
47
    }
48
49
    /**
50
     * @see Normalizer
51
     *
52
     * @throws InvalidConfigException If definition is not valid.
53
     */
54 8
    public static function to(mixed $id): self
55
    {
56 8
        return new self($id);
57
    }
58
59 5
    public function resolve(ContainerInterface $container): mixed
60
    {
61 5
        return $this->definition->resolve($container);
62
    }
63
}
64