Nullable environment variable processor

This commit is contained in:
Beno!t POLASZEK 2019-01-08 11:24:53 +01:00
parent b324445d6a
commit 3a604ac392
4 changed files with 32 additions and 0 deletions

View File

@ -6,6 +6,7 @@ CHANGELOG
* added `%env(trim:...)%` processor to trim a string value
* added `%env(default:...)%` processor to fallback to a default value
* added `%env(nullable:...)%` processor to allow empty variables to be processed as null values
4.2.0
-----

View File

@ -41,6 +41,7 @@ class EnvVarProcessor implements EnvVarProcessorInterface
'int' => 'int',
'json' => 'array',
'key' => 'bool|int|float|string|array',
'nullable' => 'bool|int|float|string|array',
'resolve' => 'string',
'default' => 'bool|int|float|string|array',
'string' => 'string',
@ -195,6 +196,10 @@ class EnvVarProcessor implements EnvVarProcessorInterface
return str_getcsv($env);
}
if ('nullable' === $prefix) {
return '' === $env ? null : $env;
}
if ('trim' === $prefix) {
return trim($env);
}

View File

@ -39,6 +39,7 @@ class RegisterEnvVarProcessorsPassTest extends TestCase
'int' => ['int'],
'json' => ['array'],
'key' => ['bool', 'int', 'float', 'string', 'array'],
'nullable' => ['bool', 'int', 'float', 'string', 'array'],
'resolve' => ['string'],
'default' => ['bool', 'int', 'float', 'string', 'array'],
'string' => ['string'],

View File

@ -433,4 +433,29 @@ class EnvVarProcessorTest extends TestCase
];
}));
}
/**
* @dataProvider validNullables
*/
public function testGetEnvNullable($value, $processed)
{
$processor = new EnvVarProcessor(new Container());
$result = $processor->getEnv('nullable', 'foo', function ($name) use ($value) {
$this->assertSame('foo', $name);
return $value;
});
$this->assertSame($processed, $result);
}
public function validNullables()
{
return [
['hello', 'hello'],
['', null],
['null', 'null'],
['Null', 'Null'],
['NULL', 'NULL'],
];
}
}