8000 Nullable environment variable processor · symfony/symfony@3a604ac · GitHub
[go: up one dir, main page]

Skip to content

Commit 3a604ac

Browse files
committed
Nullable environment variable processor
1 parent b324445 commit 3a604ac

File tree

4 files changed

+32
-0
lines changed

4 files changed

+32
-0
lines changed

src/Symfony/Component/DependencyInjection/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ CHANGELOG
66

77
* added `%env(trim:...)%` processor to trim a string value
88
* added `%env(default:...)%` processor to fallback to a default value
9+
* added `%env(nullable:...)%` processor to allow empty variables to be processed as null values
910

1011
4.2.0
1112
-----

src/Symfony/Component/DependencyInjection/EnvVarProcessor.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ public static function getProvidedTypes()
4141
'int' => 'int',
4242
'json' => 'array',
4343
'key' => 'bool|int|float|string|array',
44+
'nullable' => 'bool|int|float|string|array',
4445
'resolve' => 'string',
4546
'default' => 'bool|int|float|string|array',
4647
'string' => 'string',
@@ -195,6 +196,10 @@ public function getEnv($prefix, $name, \Closure $getEnv)
195196
return str_getcsv($env);
196197
}
197198

199+
if ('nullable' === $prefix) {
200+
return '' === $env ? null : $env;
201+
}
202+
198203
if ('trim' === $prefix) {
199204
return trim($env);
200205
}

src/Symfony/Component/DependencyInjection/Tests/Compiler/RegisterEnvVarProcessorsPassTest.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ public function testSimpleProcessor()
3939
'int' => ['int'],
4040
'json' => ['array'],
4141
'key' => ['bool', 'int', 'float', 'string', 'array'],
42+
'nullable' => ['bool', 'int', 'float', 'string', 'array'],
4243
'resolve' => ['string'],
4344
'default' => ['bool', 'int', 'float', 'string', 'array'],
4445
'string' => [' 8000 string'],

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

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -433,4 +433,29 @@ public function testGetEnvKeyChained()
433433
];
434434
}));
435435
}
436+
437+
/**
438+
* @dataProvider validNullables
439+
*/
440+
public function testGetEnvNullable($value, $processed)
441+
{
442+
$processor = new EnvVarProcessor(new Container());
443+
$result = $processor->getEnv('nullable', 'foo', function ($name) use ($value) {
444+
$this->assertSame('foo', $name);
445+
446+
return $value;
447+
});
448+
$this->assertSame($processed, $result);
449+
}
450+
451+
public function validNullables()
452+
{
453+
return [
454+
['hello', 'hello'],
455+
['', null],
456+
['null', 'null'],
457+
['Null', 'Null'],
458+
['NULL', 'NULL'],
459+
];
460+
}
436461
}

0 commit comments

Comments
 (0)
0