Skip to content

Commit

Permalink
Optimize compiled string definitions
Browse files Browse the repository at this point in the history
 - run preg_replace_callback already during compilation
  • Loading branch information
falkenhawk authored and partikus committed Jan 13, 2023
1 parent f0ca9a0 commit db5bfea
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
18 changes: 18 additions & 0 deletions src/CompiledContainer.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Invoker\ParameterResolver\DefaultValueResolver;
use Invoker\ParameterResolver\NumericArrayResolver;
use Invoker\ParameterResolver\ResolverChain;
use Psr\Container\NotFoundExceptionInterface;

/**
* Compiled version of the dependency injection container.
Expand Down Expand Up @@ -125,4 +126,21 @@ protected function resolveFactory($callable, $entryName, array $extraParameters
throw new InvalidDefinition("Entry \"$entryName\" cannot be resolved: " . $e->getMessage());
}
}

/**
* Resolve a placeholder in string definition
* - wrap possible NotFound exception to conform to the one from StringDefinition::resolveExpression.
*/
protected function resolveStringPlaceholder($placeholder, $entryName)
{
try {
return $this->delegateContainer->get($placeholder);
} catch (NotFoundExceptionInterface $e) {
throw new DependencyException(sprintf(
"Error while parsing string expression for entry '%s': %s",
$entryName,
$e->getMessage()
), 0, $e);
}
}
}
9 changes: 6 additions & 3 deletions src/Compiler/Compiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -213,9 +213,12 @@ private function compileDefinition(string $entryName, Definition $definition) :
}
break;
case $definition instanceof StringDefinition:
$entryName = $this->compileValue($definition->getName());
$expression = $this->compileValue($definition->getExpression());
$code = 'return \DI\Definition\StringDefinition::resolveExpression(' . $entryName . ', ' . $expression . ', $this->delegateContainer);';
$expression = $definition->getExpression();
$callback = function (array $matches) use ($definition) {
return '\'.$this->resolveStringPlaceholder(' . $this->compileValue($matches[1]) . ', ' . $this->compileValue($definition->getName()) . ').\'';
};
$value = preg_replace_callback('#\{([^\{\}]+)\}#', $callback, $expression);
$code = 'return \'' . $value . '\';';
break;
case $definition instanceof EnvironmentVariableDefinition:
$variableName = $this->compileValue($definition->getVariableName());
Expand Down

0 comments on commit db5bfea

Please sign in to comment.