8000 [DependencyInjection] Fix casting scalar env vars from null by fancyweb · Pull Request #50517 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions src/Symfony/Component/DependencyInjection/EnvVarProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -181,10 +181,12 @@ public function getEnv(string $prefix, string $name, \Closure $getEnv)
throw new RuntimeException(sprintf('Unsupported env var prefix "%s".', $prefix));
}

return null;
if (!\in_array($prefix, ['string', 'bool', 'not', 'int', 'float'], true)) {
return null;
}
}

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

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

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

return (int) $env;
}

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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -839,8 +839,8 @@ public function testEnvAreNullable()
$container->register('foo', 'stdClass')
->setPublic(true)
->setProperties([
'fake' => '%env(int:FAKE)%',
]);
'fake' => '%env(resolve:FAKE)%',
]);

$container->compile(true);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -760,4 +760,22 @@ public static function provideGetEnvUrlPath()
['blog//', 'https://symfony.com/blog//'],
];
}

/**
* @testWith ["", "string"]
* [false, "bool"]
* [true, "not"]
* [0, "int"]
* [0.0, "float"]
*/
public function testGetEnvCastsNull($expected, string $prefix)
{
$processor = new EnvVarProcessor(new Container());

$this->assertSame($expected, $processor->getEnv($prefix, 'default::FOO', static function () use ($processor) {
return $processor->getEnv('default', ':FOO', static function () {
return null;
});
}));
}
}
0