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

Reference   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 25
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
eloc 7
dl 0
loc 25
ccs 11
cts 11
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A to() 0 6 2
A resolve() 0 3 1
A getId() 0 3 1
A __construct() 0 3 1
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