Completed
Push — sam-rework ( 1696e6 )
by Andrii
38:13 queued 23:11
created

NamedDependency   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 13
dl 0
loc 32
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A to() 0 3 1
A resolve() 0 11 3
A __construct() 0 4 1
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\dependencies;
9
10
use Psr\Container\ContainerInterface;
11
use yii\di\Container;
12
use yii\di\contracts\DependencyInterface;
13
14
/**
15
 * Reference points to a service name in the container
16
 */
17
class NamedDependency implements DependencyInterface
18
{
19
    private $id;
20
21
    private $optional;
22
23
    /**
24
     * Constructor.
25
     * @param string $id the component ID
26
     */
27
    public function __construct(string $id, bool $optional)
28
    {
29
        $this->id = $id;
30
        $this->optional = $optional;
31
    }
32
33
    public static function to(string $id)
34
    {
35
        return new self($id, false);
36
    }
37
38
    public function resolve(ContainerInterface $container)
39
    {
40
        try {
41
            $result = $container->get($this->id);
42
        } catch (\Throwable $t) {
43
            if ($this->optional) {
44
                return null;
45
            }
46
            throw $t;
47
        }
48
        return $result;
49
    }
50
}
51