Completed
Push — master ( 4e1fd0...6b9342 )
by Matthieu
02:24
created

StringDefinition::setName()   A

Complexity

Conditions 1
Paths 1

Duplication

Lines 0
Ratio 0 %

Size

Total Lines 4
Code Lines 2

Importance

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