Passed
Pull Request — master (#43)
by Sergei
02:19
created

Reference::to()   A

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\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
    private bool $optional;
33
34
    /**
35
     * @param mixed $id
36
     *
37
     * @throws InvalidConfigException
38
     */
39 10
    private function __construct($id, bool $optional)
40
    {
41 10
        if (!is_string($id)) {
42 1
            throw new InvalidConfigException('Reference ID must be string.');
43
        }
44
45 9
        $this->id = $id;
46 9
        $this->optional = $optional;
47
    }
48
49
    /**
50
     * @throws InvalidConfigException If ID is not string.
51
     */
52 9
    public static function to($id): self
53
    {
54 9
        return new self($id, false);
55
    }
56
57
    /**
58
     * Optional reference returns `null` when there is no corresponding definition in container.
59
     *
60
     * @param mixed $id ID of the service or object to point to.
61
     *
62
     * @throws InvalidConfigException If ID is not string.
63
     */
64 1
    public static function optional($id): self
65
    {
66 1
        return new self($id, true);
67
    }
68
69 3
    public function resolve(ContainerInterface $container)
70
    {
71 3
        return (!$this->optional || $container->has($this->id)) ? $container->get($this->id) : null;
72
    }
73
}
74