8000 [DependencyInjection] Allow casting env var processors to cast null · symfony/symfony@dafa2c4 · GitHub
[go: up one dir, main page]

Skip to content

Commit dafa2c4

Browse files
committed
[DependencyInjection] Allow casting env var processors to cast null
1 parent fb32b92 commit dafa2c4

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

src/Symfony/Component/DependencyInjection/EnvVarProcessor.php

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -181,10 +181,12 @@ public function getEnv(string $prefix, string $name, \Closure $getEnv)
181181
throw new RuntimeException(sprintf('Unsupported env var prefix "%s".', $prefix));
182182
}
183183

184-
return null;
184+
if (!\in_array($prefix, ['string', 'bool', 'not', 'int', 'float'], true)) {
185+
return null;
186+
}
185187
}
186188

187-
if (!\is_scalar($env)) {
189+
if (null !== $env && !\is_scalar($env)) {
188190
throw new RuntimeException(sprintf('Non-scalar env var "%s" cannot be cast to "%s".', $name, $prefix));
189191
}
190192

@@ -199,15 +201,15 @@ public function getEnv(string $prefix, string $name, \Closure $getEnv)
199201
}
200202

201203
if ('int' === $prefix) {
202-
if (false === $env = filter_var($env, \FILTER_VALIDATE_INT) ?: filter_var($env, \FILTER_VALIDATE_FLOAT)) {
204+
if (null !== $env && false === $env = filter_var($env, \FILTER_VALIDATE_INT) ?: filter_var($env, \FILTER_VALIDATE_FLOAT)) {
203205
throw new RuntimeException(sprintf('Non-numeric env var "%s" cannot be cast to int.', $name));
204206
}
205207

206208
return (int) $env;
207209
}
208210

209211
if ('float' === $prefix) {
210-
if (false === $env = filter_var($env, \FILTER_VALIDATE_FLOAT)) {
212+
if (null !== $env && false === $env = filter_var($env, \FILTER_VALIDATE_FLOAT)) {
211213
throw new RuntimeException(sprintf('Non-numeric env var "%s" cannot be cast to float.', $name));
212214
}
213215

src/Symfony/Component/DependencyInjection/Tests/EnvVarProcessorTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -760,4 +760,18 @@ public static function provideGetEnvUrlPath()
760760
['blog//', 'https://symfony.com/blog//'],
761761
];
762762
}
763+
764+
/**
765+
* @testWith ["", "string"]
766+
* [false, "bool"]
767+
* [true, "not"]
768+
* [0, "int"]
769+
* [0.0, "float"]
770+
*/
771+
public function testGetEnvCastsNull(string|bool|int|float $expected, string $prefix)
772+
{
773+
$processor = new EnvVarProcessor(new Container());
774+
775+
$this->assertSame($expected, $processor->getEnv($prefix, 'default::FOO', static fn () => $processor->getEnv('default', ':FOO', static fn () => null)));
776+
}
763777
}

0 commit comments

Comments
 (0)
0