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

ClassDependency::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 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\dependencies;
9
10
use Psr\Container\ContainerInterface;
11
use yii\di\contracts\DependencyInterface;
12
use yii\di\exceptions\InvalidConfigException;
13
14
/**
15
 * Reference points to a class name in the container
16
 */
17
class ClassDependency implements DependencyInterface
18
{
19
    private $class;
20
21
    private $optional;
22
23
    /**
24
     * Constructor.
25
     * @param string $class the class name
26
     */
27
    public function __construct(string $class, bool $optional)
28
    {
29
        $this->class = $class;
30
        $this->optional = $optional;
31
    }
32
33
    public function resolve(ContainerInterface $container)
34
    {
35
        try {
36
            $result = $container->get($this->class);
37
        } catch (\Throwable $t) {
38
            if ($this->optional) {
39
                return null;
40
            }
41
            throw $t;
42
        }
43
44
        if (!$result instanceof $this->class) {
45
            throw new InvalidConfigException('Container returned incorrect type for service ' . $this->class);
46
        }
47
        return $result;
48
    }
49
}
50