From 93c25f887249ff9944ea02d1fa8aa1f41e97844e Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Tue, 8 Nov 2016 09:48:20 +0100 Subject: [PATCH] [DI] Force env params to be string|null --- .../EnvPlaceholderParameterBag.php | 22 +++++++++++++++++++ .../EnvPlaceholderParameterBagTest.php | 21 ++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/src/Symfony/Component/DependencyInjection/ParameterBag/EnvPlaceholderParameterBag.php b/src/Symfony/Component/DependencyInjection/ParameterBag/EnvPlaceholderParameterBag.php index be52608cbd..0e7b116b6c 100644 --- a/src/Symfony/Component/DependencyInjection/ParameterBag/EnvPlaceholderParameterBag.php +++ b/src/Symfony/Component/DependencyInjection/ParameterBag/EnvPlaceholderParameterBag.php @@ -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))); + } + } + } } diff --git a/src/Symfony/Component/DependencyInjection/Tests/ParameterBag/EnvPlaceholderParameterBagTest.php b/src/Symfony/Component/DependencyInjection/Tests/ParameterBag/EnvPlaceholderParameterBagTest.php index 6b4d590e85..6f055dab7d 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/ParameterBag/EnvPlaceholderParameterBagTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/ParameterBag/EnvPlaceholderParameterBagTest.php @@ -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(); + } }