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

NamedClassDependency::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 3
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
use yii\di\exceptions\InvalidConfigException;
14
15
/**
16
 * Dependency points a service with a given class in the container which must implement a given class
17
 */
18
class NamedClassDependency implements DependencyInterface
19
{
20
    private $id;
21
22
    private $class;
23
24
    private $optional;
25
26
    /**
27
     * Constructor.
28
     * @param string $id the component ID
29
     */
30
    public function __construct(string $id, string $class, bool $optional)
31
    {
32
        $this->id = $id;
33
        $this->class = $class;
34
        $this->optional = $optional;
35
    }
36
37
    public static function to(string $id, string $class)
38
    {
39
        return new self($id, $class, false);
40
    }
41
42
    public function resolve(ContainerInterface $container)
43
    {
44
        try {
45
            $result = $container->get($this->id);
46
        } catch (\Throwable $t) {
47
            if ($this->optional) {
48
                return null;
49
            }
50
            throw $t;
51
        }
52
53
        if (!$result instanceof $this->class) {
54
            throw new InvalidConfigException(strtr('Container returned incorrect type for service {s}, expected {e}, got {r}', [
55
                '{s}' => $this->id,
56
                '{e}' => $this->class,
57
                '{r}' => get_class($result)
58
            ]));
59
        }
60
        return $result;
61
    }
62
}
63