Skip to content

Commit

Permalink
[DependencyInjection] Add defined prefix for env var processor
Browse files Browse the repository at this point in the history
  • Loading branch information
GaryPEGEOT authored and nicolas-grekas committed Jun 28, 2023
1 parent 65fa483 commit 473fc19
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/Symfony/Component/DependencyInjection/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ CHANGELOG
---

* Deprecate `ContainerAwareInterface` and `ContainerAwareTrait`, use dependency injection instead
* Add `defined` env var processor that returns `true` for defined and neither null nor empty env vars

6.3
---
Expand Down
9 changes: 9 additions & 0 deletions src/Symfony/Component/DependencyInjection/EnvVarProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ public static function getProvidedTypes(): array
'require' => 'bool|int|float|string|array',
'enum' => \BackedEnum::class,
'shuffle' => 'array',
'defined' => 'bool',
];
}

Expand Down Expand Up @@ -103,6 +104,14 @@ public function getEnv(string $prefix, string $name, \Closure $getEnv): mixed
return $backedEnumClassName::tryFrom($backedEnumValue) ?? throw new RuntimeException(sprintf('Enum value "%s" is not backed by "%s".', $backedEnumValue, $backedEnumClassName));
}

if ('defined' === $prefix) {
try {
return '' !== ($getEnv($name) ?? '');
} catch (EnvNotFoundException) {
return false;
}
}

if ('default' === $prefix) {
if (false === $i) {
throw new RuntimeException(sprintf('Invalid env "default:%s": a fallback parameter should be provided.', $name));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public function testSimpleProcessor()
'require' => ['bool', 'int', 'float', 'string', 'array'],
'enum' => [\BackedEnum::class],
'shuffle' => ['array'],
'defined' => ['bool'],
];

$this->assertSame($expected, $container->getParameterBag()->getProvidedTypes());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -925,4 +925,21 @@ public function testGetEnvCastsNull($expected, string $prefix)
});
}));
}

/**
* @dataProvider provideGetEnvDefined
*/
public function testGetEnvDefined(bool $expected, callable $callback)
{
$this->assertSame($expected, (new EnvVarProcessor(new Container()))->getEnv('defined', 'NO_SOMETHING', $callback));
}

public static function provideGetEnvDefined(): iterable
{
yield 'Defined' => [true, fn () => 'foo'];
yield 'Falsy but defined' => [true, fn () => '0'];
yield 'Empty string' => [false, fn () => ''];
yield 'Null' => [false, fn () => null];
yield 'Env var not defined' => [false, fn () => throw new EnvNotFoundException()];
}
}

0 comments on commit 473fc19

Please sign in to comment.