Skip to content

Commit 5d3f9d4

Browse files
bpolaszekfabpot
authored andcommitted
[DependencyInjection] Negated (not:) env var processor
1 parent 154ae8c commit 5d3f9d4

File tree

4 files changed

+23
-2
lines changed

4 files changed

+23
-2
lines changed

CHANGELOG.md

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

77
* Add `ServicesConfigurator::remove()` in the PHP-DSL
8+
* added `%env(not:...)%` processor to negate boolean values
89

910
5.2.0
1011
-----

EnvVarProcessor.php

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ public static function getProvidedTypes()
4141
return [
4242
'base64' => 'string',
4343
'bool' => 'bool',
44+
'not' => 'bool',
4445
'const' => 'bool|int|float|string|array',
4546
'csv' => 'array',
4647
'file' => 'string',
@@ -191,8 +192,10 @@ public function getEnv(string $prefix, string $name, \Closure $getEnv)
191192
return (string) $env;
192193
}
193194

194-
if ('bool' === $prefix) {
195-
return (bool) (filter_var($env, \FILTER_VALIDATE_BOOLEAN) ?: filter_var($env, \FILTER_VALIDATE_INT) ?: filter_var($env, \FILTER_VALIDATE_FLOAT));
195+
if (in_array($prefix, ['bool', 'not'], true)) {
196+
$env = (bool) (filter_var($env, \FILTER_VALIDATE_BOOLEAN) ?: filter_var($env, \FILTER_VALIDATE_INT) ?: filter_var($env, \FILTER_VALIDATE_FLOAT));
197+
198+
return 'not' === $prefix ? !$env : $env;
196199
}
197200

198201
if ('int' === $prefix) {

Tests/Compiler/RegisterEnvVarProcessorsPassTest.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ public function testSimpleProcessor()
3333
'foo' => ['string'],
3434
'base64' => ['string'],
3535
'bool' => ['bool'],
36+
'not' => ['bool'],
3637
'const' => ['bool', 'int', 'float', 'string', 'array'],
3738
'csv' => ['array'],
3839
'file' => ['string'],

Tests/EnvVarProcessorTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,22 @@ public function testGetEnvBool($value, $processed)
6464
$this->assertSame($processed, $result);
6565
}
6666

67+
/**
68+
* @dataProvider validBools
69+
*/
70+
public function testGetEnvNot($value, $processed)
71+
{
72+
$processor = new EnvVarProcessor(new Container());
73+
74+
$result = $processor->getEnv('not', 'foo', function ($name) use ($value) {
75+
$this->assertSame('foo', $name);
76+
77+
return $value;
78+
});
79+
80+
$this->assertSame(!$processed, $result);
81+
}
82+
6783
public function validBools()
6884
{
6985
return [

0 commit comments

Comments
 (0)