Skip to content

[DI] Allow processing env vars #23901

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 7, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\EnvVarProcessorInterface;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Reference;
Expand Down Expand Up @@ -283,6 +284,8 @@ public function load(array $configs, ContainerBuilder $container)
->addTag('console.command');
$container->registerForAutoconfiguration(ResourceCheckerInterface::class)
->addTag('config_cache.resource_checker');
$container->registerForAutoconfiguration(EnvVarProcessorInterface::class)
->addTag('container.env_var_processor');
$container->registerForAutoconfiguration(ServiceSubscriberInterface::class)
->addTag('container.service_subscriber');
$container->registerForAutoconfiguration(ArgumentValueResolverInterface::class)
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Component/DependencyInjection/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ CHANGELOG
3.4.0
-----

* added `EnvVarProcessorInterface` and corresponding "container.env_var_processor" tag for processing env vars
* added support for ignore-on-uninitialized references
* deprecated service auto-registration while autowiring
* deprecated the ability to check for the initialization of a private service with the `Container::initialized()` method
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ public function __construct()
100 => array(
$resolveClassPass = new ResolveClassPass(),
new ResolveInstanceofConditionalsPass(),
new RegisterEnvVarProcessorsPass(),
),
);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\EnvVarProcessorInterface;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBag;
use Symfony\Component\DependencyInjection\ServiceLocator;
use Symfony\Component\DependencyInjection\Reference;

/**
* Creates the container.env_var_processors_locator service.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
class RegisterEnvVarProcessorsPass implements CompilerPassInterface
{
private static $allowedTypes = array('array', 'bool', 'float', 'int', 'string');

public function process(ContainerBuilder $container)
{
$bag = $container->getParameterBag();
$types = array();
$processors = array();
foreach ($container->findTaggedServiceIds('container.env_var_processor') as $id => $tags) {
foreach ($tags as $attr) {
if (!$r = $container->getReflectionClass($class = $container->getDefinition($id)->getClass())) {
throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id));
} elseif (!$r->isSubclassOf(EnvVarProcessorInterface::class)) {
throw new InvalidArgumentException(sprintf('Service "%s" must implement interface "%s".', $id, EnvVarProcessorInterface::class));
}
foreach ($class::getProvidedTypes() as $prefix => $type) {
$processors[$prefix] = new ServiceClosureArgument(new Reference($id));
$types[$prefix] = self::validateProvidedTypes($type, $class);
}
}
}

if ($processors) {
if ($bag instanceof EnvPlaceholderParameterBag) {
$bag->setProvidedTypes($types);
}
$container->register('container.env_var_processors_locator', ServiceLocator::class)
->setArguments(array($processors))
;
}
}

private static function validateProvidedTypes($types, $class)
{
$types = explode('|', $types);

foreach ($types as $type) {
if (!in_array($type, self::$allowedTypes)) {
throw new InvalidArgumentException(sprintf('Invalid type "%s" returned by "%s::getProvidedTypes()", expected one of "%s".', $type, $class, implode('", "', self::$allowedTypes)));
}
}

return $types;
}
}
37 changes: 27 additions & 10 deletions src/Symfony/Component/DependencyInjection/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use Symfony\Component\DependencyInjection\Exception\EnvNotFoundException;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
Expand Down Expand Up @@ -48,6 +49,7 @@ class Container implements ResettableContainerInterface
protected $methodMap = array();
protected $aliases = array();
protected $loading = array();
protected $resolving = array();

/**
* @internal
Expand All @@ -62,6 +64,7 @@ class Container implements ResettableContainerInterface
private $underscoreMap = array('_' => '', '.' => '_', '\\' => '_');
private $envCache = array();
private $compiled = false;
private $getEnv;

/**
* @param ParameterBagInterface $parameterBag A ParameterBagInterface instance
Expand Down Expand Up @@ -438,23 +441,37 @@ protected function load($file)
*/
protected function getEnv($name)
{
if (isset($this->resolving[$envName = "env($name)"])) {
throw new ParameterCircularReferenceException(array_keys($this->resolving));
}
if (isset($this->envCache[$name]) || array_key_exists($name, $this->envCache)) {
return $this->envCache[$name];
}
if (isset($_SERVER[$name]) && 0 !== strpos($name, 'HTTP_')) {
return $this->envCache[$name] = $_SERVER[$name];
}
if (isset($_ENV[$name])) {
return $this->envCache[$name] = $_ENV[$name];
if (!$this->has($id = 'container.env_var_processors_locator')) {
$this->set($id, new ServiceLocator(array()));
}
if (false !== ($env = getenv($name)) && null !== $env) { // null is a possible value because of thread safety issues
return $this->envCache[$name] = $env;
if (!$this->getEnv) {
$this->getEnv = new \ReflectionMethod($this, __FUNCTION__);
$this->getEnv->setAccessible(true);
$this->getEnv = $this->getEnv->getClosure($this);
}
if (!$this->hasParameter("env($name)")) {
throw new EnvNotFoundException($name);
$processors = $this->get($id);

if (false !== $i = strpos($name, ':')) {
$prefix = substr($name, 0, $i);
$localName = substr($name, 1 + $i);
} else {
$prefix = 'string';
$localName = $name;
}
$processor = $processors->has($prefix) ? $processors->get($prefix) : new EnvVarProcessor($this);

return $this->envCache[$name] = $this->getParameter("env($name)");
$this->resolving[$envName] = true;
try {
return $this->envCache[$name] = $processor->getEnv($prefix, $localName, $this->getEnv);
} finally {
unset($this->resolving[$envName]);
}
}

/**
Expand Down
14 changes: 10 additions & 4 deletions src/Symfony/Component/DependencyInjection/ContainerBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -1472,20 +1472,26 @@ public static function hash($value)
protected function getEnv($name)
{
$value = parent::getEnv($name);
$bag = $this->getParameterBag();

if (!is_string($value) || !$this->getParameterBag() instanceof EnvPlaceholderParameterBag) {
if (!is_string($value) || !$bag instanceof EnvPlaceholderParameterBag) {
return $value;
}

foreach ($this->getParameterBag()->getEnvPlaceholders() as $env => $placeholders) {
foreach ($bag->getEnvPlaceholders() as $env => $placeholders) {
if (isset($placeholders[$value])) {
$bag = new ParameterBag($this->getParameterBag()->all());
$bag = new ParameterBag($bag->all());

return $bag->unescapeValue($bag->get("env($name)"));
}
}

return $value;
$this->resolving["env($name)"] = true;
try {
return $bag->unescapeValue($this->resolveEnvPlaceholders($bag->escapeValue($value), true));
} finally {
unset($this->resolving["env($name)"]);
}
}

/**
Expand Down
15 changes: 9 additions & 6 deletions src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php
Original file line number Diff line number Diff line change
Expand Up @@ -1112,7 +1112,7 @@ private function addDefaultParametersMethod()
$export = $this->exportParameters(array($value));
$export = explode('0 => ', substr(rtrim($export, " )\n"), 7, -1), 2);

if (preg_match("/\\\$this->(?:getEnv\('\w++'\)|targetDirs\[\d++\])/", $export[1])) {
if (preg_match("/\\\$this->(?:getEnv\('(?:\w++:)*+\w++'\)|targetDirs\[\d++\])/", $export[1])) {
$dynamicPhp[$key] = sprintf('%scase %s: $value = %s; break;', $export[0], $this->export($key), $export[1]);
} else {
$php[] = sprintf('%s%s => %s,', $export[0], $this->export($key), $export[1]);
Expand Down Expand Up @@ -1685,7 +1685,7 @@ private function dumpParameter($name)
return $dumpedValue;
}

if (!preg_match("/\\\$this->(?:getEnv\('\w++'\)|targetDirs\[\d++\])/", $dumpedValue)) {
if (!preg_match("/\\\$this->(?:getEnv\('(?:\w++:)*+\w++'\)|targetDirs\[\d++\])/", $dumpedValue)) {
return sprintf("\$this->parameters['%s']", $name);
}
}
Expand Down Expand Up @@ -1880,13 +1880,16 @@ private function doExport($value)
{
$export = var_export($value, true);

if ("'" === $export[0] && $export !== $resolvedExport = $this->container->resolveEnvPlaceholders($export, "'.\$this->getEnv('%s').'")) {
if ("'" === $export[0] && $export !== $resolvedExport = $this->container->resolveEnvPlaceholders($export, "'.\$this->getEnv('string:%s').'")) {
$export = $resolvedExport;
if ("'" === $export[1]) {
$export = substr($export, 3);
}
if (".''" === substr($export, -3)) {
$export = substr($export, 0, -3);
if ("'" === $export[1]) {
$export = substr_replace($export, '', 18, 7);
}
}
if ("'" === $export[1]) {
$export = substr($export, 3);
}
}

Expand Down
Loading