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

NamedDependency::resolve()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 11
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 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