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

Reference   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

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

4 Methods

Rating   Name   Duplication   Size   Complexity  
A optional() 0 3 1
A __construct() 0 8 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
    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