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

ClassDefinition   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 14
dl 0
loc 31
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A resolve() 0 15 4
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