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