[DI] Force env params to be string|null

This commit is contained in:
Nicolas Grekas 2016-11-08 09:48:20 +01:00
parent b376d92320
commit 93c25f8872
2 changed files with 43 additions and 0 deletions

View File

@ -79,4 +79,26 @@ class EnvPlaceholderParameterBag extends ParameterBag
}
}
}
/**
* {@inheritdoc}
*/
public function resolve()
{
if ($this->resolved) {
return;
}
parent::resolve();
foreach ($this->envPlaceholders as $env => $placeholders) {
if (!isset($this->parameters[$name = strtolower("env($env)")])) {
continue;
}
if (is_numeric($default = $this->parameters[$name])) {
$this->parameters[$name] = (string) $default;
} elseif (!is_string($default)) {
throw new RuntimeException(sprintf('The default value of env parameter "%s" must be string or null, %s given.', $env, gettype($default)));
}
}
}
}

View File

@ -109,4 +109,25 @@ class EnvPlaceholderParameterBagTest extends \PHPUnit_Framework_TestCase
$this->assertNotEquals($firstPlaceholder, $secondPlaceholder);
$this->assertCount(2, $merged[$envName]);
}
public function testResolveEnvCastsIntToString()
{
$bag = new EnvPlaceholderParameterBag();
$bag->get('env(INT)');
$bag->set('env(INT)', 2);
$bag->resolve();
$this->assertSame('2', $bag->all()['env(int)']);
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
* @expectedExceptionMessage The default value of env parameter "ARRAY" must be string or null, array given.
*/
public function testResolveThrowsOnBadDefaultValue()
{
$bag = new EnvPlaceholderParameterBag();
$bag->get('env(ARRAY)');
$bag->set('env(ARRAY)', array());
$bag->resolve();
}
}