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

Skip to content

Commit 6277c6d

Browse files
committed
[DependencyInjection] Allow casting env var processors to cast null
1 parent 2e688f7 commit 6277c6d

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

src/Symfony/Component/DependencyInjection/EnvVarProcessor.php

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,10 @@ public function getEnv(string $prefix, string $name, \Closure $getEnv): mixed
196196
throw new RuntimeException(sprintf('Unsupported env var prefix "%s".', $prefix));
197197
}
198198

199+
if (\in_array($prefix, ['string', 'bool', 'not', 'int', 'float'], true)) {
200+
goto cast;
201+
}
202+
199203
return null;
200204
}
201205

@@ -209,6 +213,7 @@ public function getEnv(string $prefix, string $name, \Closure $getEnv): mixed
209213
throw new RuntimeException(sprintf('Non-scalar env var "%s" cannot be cast to "%s".', $name, $prefix));
210214
}
211215

216+
cast:
212217
if ('string' === $prefix) {
213218
return (string) $env;
214219
}
@@ -220,15 +225,15 @@ public function getEnv(string $prefix, string $name, \Closure $getEnv): mixed
220225
}
221226

222227
if ('int' === $prefix) {
223-
if (false === $env = filter_var($env, \FILTER_VALIDATE_INT) ?: filter_var($env, \FILTER_VALIDATE_FLOAT)) {
228+
if (null !== $env && false === $env = filter_var($env, \FILTER_VALIDATE_INT) ?: filter_var($env, \FILTER_VALIDATE_FLOAT)) {
224229
throw new RuntimeException(sprintf('Non-numeric env var "%s" cannot be cast to int.', $name));
225230
}
226231

227232
return (int) $env;
228233
}
229234

230235
if ('float' === $prefix) {
231-
if (false === $env = filter_var($env, \FILTER_VALIDATE_FLOAT)) {
236+
if (null !== $env && false === $env = filter_var($env, \FILTER_VALIDATE_FLOAT)) {
232237
throw new RuntimeException(sprintf('Non-numeric env var "%s" cannot be cast to float.', $name));
233238
}
234239

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -845,4 +845,18 @@ public static function provideGetEnvUrlPath()
845845
['blog//', 'https://symfony.com/blog//'],
846846
];
847847
}
848+
849+
/**
850+
* @testWith ["", "string"]
851+
* [false, "bool"]
852+
* [true, "not"]
853+
* [0, "int"]
854+
* [0.0, "float"]
855+
*/
856+
public function testGetEnvCastsNull(string|bool|int|float $expected, string $prefix)
857+
{
858+
$processor = new EnvVarProcessor(new Container());
859+
860+
$this->assertSame($expected, $processor->getEnv($prefix, 'default::FOO', static fn () => $processor->getEnv('default', ':FOO', static fn () => null)));
861+
}
848862
}

0 commit comments

Comments
 (0)
0