From d04cb7b0e08799d94a523dfccdad51679c5f33df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriel=20Ostroluck=C3=BD?= Date: Thu, 7 Jul 2022 23:13:47 +0200 Subject: [PATCH] [DependencyInjection] Add `shuffle` env processor --- .../Component/DependencyInjection/CHANGELOG.md | 1 + .../DependencyInjection/EnvVarProcessor.php | 7 +++++++ .../Tests/EnvVarProcessorTest.php | 17 +++++++++++++++++ 3 files changed, 25 insertions(+) diff --git a/src/Symfony/Component/DependencyInjection/CHANGELOG.md b/src/Symfony/Component/DependencyInjection/CHANGELOG.md index ce6a726d7777a..e72239311e298 100644 --- a/src/Symfony/Component/DependencyInjection/CHANGELOG.md +++ b/src/Symfony/Component/DependencyInjection/CHANGELOG.md @@ -6,6 +6,7 @@ CHANGELOG * Add argument `&$asGhostObject` to LazyProxy's `DumperInterface` to allow using ghost objects for lazy loading services * Add `enum` env var processor + * Add `shuffle` env var processor 6.1 --- diff --git a/src/Symfony/Component/DependencyInjection/EnvVarProcessor.php b/src/Symfony/Component/DependencyInjection/EnvVarProcessor.php index efe22a87e603f..9cbd9fd3f79d2 100644 --- a/src/Symfony/Component/DependencyInjection/EnvVarProcessor.php +++ b/src/Symfony/Component/DependencyInjection/EnvVarProcessor.php @@ -58,6 +58,7 @@ public static function getProvidedTypes(): array 'trim' => 'string', 'require' => 'bool|int|float|string|array', 'enum' => \BackedEnum::class, + 'shuffle' => 'array', ]; } @@ -206,6 +207,12 @@ public function getEnv(string $prefix, string $name, \Closure $getEnv): mixed return null; } + if ('shuffle' === $prefix) { + \is_array($env) ? shuffle($env) : throw new RuntimeException(sprintf('Env var "%s" cannot be shuffled, expected array, got "%s".', $name, get_debug_type($env))); + + return $env; + } + if (!\is_scalar($env)) { throw new RuntimeException(sprintf('Non-scalar env var "%s" cannot be cast to "%s".', $name, $prefix)); } diff --git a/src/Symfony/Component/DependencyInjection/Tests/EnvVarProcessorTest.php b/src/Symfony/Component/DependencyInjection/Tests/EnvVarProcessorTest.php index 35c49d554f075..0ea6aa5679096 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/EnvVarProcessorTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/EnvVarProcessorTest.php @@ -708,6 +708,23 @@ public function testGetEnvCsv($value, $processed) $this->assertSame($processed, $result); } + public function testGetEnvShuffle() + { + mt_srand(2); + + $this->assertSame( + ['bar', 'foo'], + (new EnvVarProcessor(new Container()))->getEnv('shuffle', '', fn () => ['foo', 'bar']), + ); + } + + public function testGetEnvShuffleInvalid() + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Env var "foo" cannot be shuffled, expected array, got "string".'); + (new EnvVarProcessor(new Container()))->getEnv('shuffle', 'foo', fn () => 'bar'); + } + public function validCsv() { $complex = <<<'CSV'