[DI] Allow null as default env value

This commit is contained in:
Samuel ROZE 2016-11-22 12:01:02 +00:00 committed by Nicolas Grekas
parent 59f99493f8
commit 519a47179a
2 changed files with 27 additions and 5 deletions

View File

@ -41,8 +41,8 @@ class EnvPlaceholderParameterBag extends ParameterBag
if ($this->has($name)) {
$defaultValue = parent::get($name);
if (!is_scalar($defaultValue)) {
throw new RuntimeException(sprintf('The default value of an env() parameter must be scalar, but "%s" given to "%s".', gettype($defaultValue), $name));
if (null !== $defaultValue && !is_scalar($defaultValue)) {
throw new RuntimeException(sprintf('The default value of an env() parameter must be scalar or null, but "%s" given to "%s".', gettype($defaultValue), $name));
}
}
@ -96,8 +96,8 @@ class EnvPlaceholderParameterBag extends ParameterBag
}
if (is_numeric($default = $this->parameters[$name])) {
$this->parameters[$name] = (string) $default;
} elseif (null !== $default && !is_string($default)) {
throw new RuntimeException(sprintf('The default value of env parameter "%s" must be string or null, %s given.', $env, gettype($default)));
} elseif (null !== $default && !is_scalar($default)) {
throw new RuntimeException(sprintf('The default value of env parameter "%s" must be scalar or null, %s given.', $env, gettype($default)));
}
}
}

View File

@ -130,7 +130,7 @@ class EnvPlaceholderParameterBagTest extends \PHPUnit_Framework_TestCase
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
* @expectedExceptionMessage The default value of env parameter "ARRAY_VAR" must be string or null, array given.
* @expectedExceptionMessage The default value of env parameter "ARRAY_VAR" must be scalar or null, array given.
*/
public function testResolveThrowsOnBadDefaultValue()
{
@ -139,4 +139,26 @@ class EnvPlaceholderParameterBagTest extends \PHPUnit_Framework_TestCase
$bag->set('env(Array_Var)', array());
$bag->resolve();
}
public function testGetEnvAllowsNull()
{
$bag = new EnvPlaceholderParameterBag();
$bag->set('env(NULL_VAR)', null);
$bag->get('env(NULL_VAR)');
$bag->resolve();
$this->assertNull($bag->all()['env(null_var)']);
}
/**
* @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
* @expectedExceptionMessage The default value of an env() parameter must be scalar or null, but "array" given to "env(ARRAY_VAR)".
*/
public function testGetThrowsOnBadDefaultValue()
{
$bag = new EnvPlaceholderParameterBag();
$bag->set('env(ARRAY_VAR)', array());
$bag->get('env(ARRAY_VAR)');
$bag->resolve();
}
}