Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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 <matthieu@mnapoli.fr>
16
 */
17
class StringDefinition implements Definition, SelfResolvingDefinition
18
{
19
    /** Entry name. */
20
    private string $name = '';
21
 
22
    public function __construct(
23
        private string $expression,
24
    ) {
25
    }
26
 
27
    public function getName() : string
28
    {
29
        return $this->name;
30
    }
31
 
32
    public function setName(string $name) : void
33
    {
34
        $this->name = $name;
35
    }
36
 
37
    public function getExpression() : string
38
    {
39
        return $this->expression;
40
    }
41
 
42
    public function resolve(ContainerInterface $container) : string
43
    {
44
        return self::resolveExpression($this->name, $this->expression, $container);
45
    }
46
 
47
    public function isResolvable(ContainerInterface $container) : bool
48
    {
49
        return true;
50
    }
51
 
52
    public function replaceNestedDefinitions(callable $replacer) : void
53
    {
54
        // no nested definitions
55
    }
56
 
57
    public function __toString() : string
58
    {
59
        return $this->expression;
60
    }
61
 
62
    /**
63
     * Resolve a string expression.
64
     */
65
    public static function resolveExpression(
66
        string $entryName,
67
        string $expression,
68
        ContainerInterface $container
69
    ) : string {
70
        $callback = function (array $matches) use ($entryName, $container) {
71
            /** @psalm-suppress InvalidCatch */
72
            try {
73
                return $container->get($matches[1]);
74
            } catch (NotFoundExceptionInterface $e) {
75
                throw new DependencyException(sprintf(
76
                    "Error while parsing string expression for entry '%s': %s",
77
                    $entryName,
78
                    $e->getMessage()
79
                ), 0, $e);
80
            }
81
        };
82
 
83
        $result = preg_replace_callback('#\{([^{}]+)}#', $callback, $expression);
84
        if ($result === null) {
85
            throw new \RuntimeException(sprintf('An unknown error occurred while parsing the string definition: \'%s\'', $expression));
86
        }
87
 
88
        return $result;
89
    }
90
}