Reference   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
dl 0
loc 39
ccs 10
cts 10
cp 1
rs 10
c 1
b 0
f 0
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A optional() 0 3 1
A __construct() 0 7 2
A to() 0 3 1
A resolve() 0 3 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Definitions;
6
7
use Psr\Container\ContainerInterface;
8
use Yiisoft\Definitions\Contract\ReferenceInterface;
9
use Yiisoft\Definitions\Exception\InvalidConfigException;
10
11
use function is_string;
12
13
/**
14
 * The `Reference` defines a dependency to a service in the container or factory in another service definition.
15
 * For example:
16
 *
17
 * ```php
18
 * [
19
 *    InterfaceA::class => ConcreteA::class,
20
 *    'alternativeForA' => ConcreteB::class,
21
 *    MyService::class => [
22
 *        '__construct()' => [
23
 *            Reference::to('alternativeForA'),
24
 *        ],
25
 *    ],
26
 * ]
27
 * ```
28
 */
29
final class Reference implements ReferenceInterface
30
{
31
    private string $id;
32
33
    /**
34
     * @throws InvalidConfigException
35
     */
36 12
    private function __construct(mixed $id, private bool $optional)
37
    {
38 12
        if (!is_string($id)) {
39 1
            throw new InvalidConfigException('Reference ID must be string.');
40
        }
41
42 11
        $this->id = $id;
43
    }
44
45
    /**
46
     * @throws InvalidConfigException If ID is not string.
47
     */
48 11
    public static function to(mixed $id): self
49
    {
50 11
        return new self($id, false);
51
    }
52
53
    /**
54
     * Optional reference returns `null` when there is no corresponding definition in container.
55
     *
56
     * @param mixed $id ID of the service or object to point to.
57
     *
58
     * @throws InvalidConfigException If ID is not string.
59
     */
60 1
    public static function optional(mixed $id): self
61
    {
62 1
        return new self($id, true);
63
    }
64
65 9
    public function resolve(ContainerInterface $container): mixed
66
    {
67 9
        return (!$this->optional || $container->has($this->id)) ? $container->get($this->id) : null;
68
    }
69
}
70