Completed
Push — sam-rework ( 7a8255...f8da6f )
by Andrii
12:42
created

ClassDefinition::resolve()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 15
rs 9.9666
c 0
b 0
f 0
cc 4
nc 4
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\definitions;
9
10
use Psr\Container\ContainerInterface;
11
use yii\di\contracts\DefinitionInterface;
12
use yii\di\exceptions\InvalidConfigException;
13
14
/**
15
 * Reference points to a class name in the container
16
 */
17
class ClassDefinition implements DefinitionInterface
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, array $params = [])
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