Passed
Pull Request — master (#78)
by Dmitriy
02:32
created

Reference::to()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Factory\Definition;
6
7
use Psr\Container\ContainerInterface;
8
use Yiisoft\Factory\Exception\InvalidConfigException;
9
10
use function is_string;
11
12
/**
13
 * Class Reference allows us to define a dependency to a service in the container in another service definition.
14
 * For example:
15
 * ```php
16
 * [
17
 *    InterfaceA::class => ConcreteA::class,
18
 *    'alternativeForA' => ConcreteB::class,
19
 *    Service1::class => [
20
 *        '__construct()' => [
21
 *            Reference::to('alternativeForA')
22
 *        ]
23
 *    ]
24
 * ]
25
 * ```
26
 */
27
class Reference implements ReferenceInterface
28
{
29
    private string $id;
30
31 13
    private function __construct(string $id)
32
    {
33 13
        $this->id = $id;
34 13
    }
35
36 1
    public function getId(): string
37
    {
38 1
        return $this->id;
39
    }
40
41 14
    public static function to($id): ReferenceInterface
42
    {
43 14
        if (!is_string($id)) {
44 1
            throw new InvalidConfigException('Reference id must be string.');
45
        }
46 13
        return new self($id);
47
    }
48
49 12
    public function resolve(ContainerInterface $container)
50
    {
51 12
        return $container->get($this->id);
52
    }
53
}
54