Completed
Push — sam-rework ( 028f23...53428e )
by Andrii
12:32
created

Reference   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
eloc 10
dl 0
loc 44
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A to() 0 3 1
A getId() 0 3 1
A resolve() 0 3 1
A __construct() 0 3 1
A __set_state() 0 9 2
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\di;
9
10
use Psr\Container\ContainerInterface;
11
use yii\di\contracts\DependencyInterface;
12
use yii\di\exceptions\InvalidConfigException;
13
14
/**
15
 * Class Reference allows us to define a dependency to a service in the container in another service definition.
16
 * For example:
17
 * ```php
18
 * [
19
 *    InterfaceA::class => ConcreteA::class,
20
 *    'alternativeForA' => ConcreteB::class,
21
 *    Service1::class => [
22
 *        '__construct()' => [
23
 *            Reference::to('alternativeForA')
24
 *        ]
25
 *    ]
26
 * ]
27
 * ```
28
 */
29
class Reference implements DependencyInterface
30
{
31
    private $id;
32
33
    private function __construct($id)
34
    {
35
        $this->id = $id;
36
    }
37
38
    public function getId(): string
39
    {
40
        return $this->id;
41
    }
42
43
    public static function to(string $id)
44
    {
45
        return new self($id);
46
    }
47
48
    /**
49
     * @param Container $container
50
     */
51
    public function resolve(ContainerInterface $container)
52
    {
53
        return $container->get($this->id);
54
    }
55
56
    /**
57
     * Restores class state after using `var_export()`.
58
     *
59
     * @param array $state
60
     * @return self
61
     * @throws InvalidConfigException when $state property does not contain `id` parameter
62
     * @see var_export()
63
     */
64
    public static function __set_state($state)
65
    {
66
        if (!isset($state['id'])) {
67
            throw new InvalidConfigException(
68
                'Failed to instantiate class "Reference". Required parameter "id" is missing'
69
            );
70
        }
71
72
        return new self($state['id']);
73
    }
74
}
75