Completed
Push — master ( a051a7...500db5 )
by Matthieu
02:31
created

StringDefinition::resolve()   A

Complexity

Conditions 3
Paths 2

Duplication

Lines 0
Ratio 0 %

Size

Total Lines 22
Code Lines 15

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 22
rs 9.2
cc 3
eloc 15
nc 2
nop 1
1
<?php
2
3
namespace DI\Definition;
4
5
use DI\DependencyException;
6
use DI\Scope;
7
use Interop\Container\ContainerInterface;
8
use Interop\Container\Exception\NotFoundException;
9
10
/**
11
 * Definition of a string composed of other strings.
12
 *
13
 * @since 5.0
14
 * @author Matthieu Napoli <[email protected]>
15
 */
16
class StringDefinition implements Definition, SelfResolvingDefinition
17
{
18
    /**
19
     * Entry name.
20
     * @var string
21
     */
22
    private $name;
23
24
    /**
25
     * @var string
26
     */
27
    private $expression;
28
29
    /**
30
     * @param string $name       Entry name
31
     * @param string $expression
32
     */
33
    public function __construct($name, $expression)
34
    {
35
        $this->name = $name;
36
        $this->expression = $expression;
37
    }
38
39
    /**
40
     * @return string Entry name
41
     */
42
    public function getName()
43
    {
44
        return $this->name;
45
    }
46
47
    /**
48
     * [email protected]}
49
     */
50
    public function getScope()
51
    {
52
        return Scope::SINGLETON;
53
    }
54
55
    /**
56
     * @return string
57
     */
58
    public function getExpression()
59
    {
60
        return $this->expression;
61
    }
62
63
    public function resolve(ContainerInterface $container)
64
    {
65
        $expression = $this->expression;
66
67
        $result = preg_replace_callback('#\{([^\{\}]+)\}#', function (array $matches) use ($container) {
68
            try {
69
                return $container->get($matches[1]);
70
            } catch (NotFoundException $e) {
71
                throw new DependencyException(sprintf(
72
                    "Error while parsing string expression for entry '%s': %s",
73
                    $this->getName(),
74
                    $e->getMessage()
75
                ), 0, $e);
76
            }
77
        }, $expression);
78
79
        if ($result === null) {
80
            throw new \RuntimeException(sprintf('An unknown error occurred while parsing the string definition: \'%s\'', $expression));
81
        }
82
83
        return $result;
84
    }
85
86
    public function isResolvable(ContainerInterface $container)
87
    {
88
        return true;
89
    }
90
}
91