Passed
Pull Request — master (#43)
by Sergei
05:11 queued 03:02
created

Reference::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 8
ccs 5
cts 5
cp 1
crap 2
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
     * @param mixed $id ID of the service or object to point to.
59
     *
60
     * @throws InvalidConfigException If ID is not string.
61
     */
62 1
    public static function optional($id): self
63
    {
64 1
        return new self($id, true);
65
    }
66
67 3
    public function resolve(ContainerInterface $container)
68
    {
69 3
        return (!$this->optional || $container->has($this->id)) ? $container->get($this->id) : null;
70
    }
71
}
72