Last active
February 1, 2021 14:54
-
-
Save dennzo/84f131aba2ed25262fffd74809788c99 to your computer and use it in GitHub Desktop.
Symfony - EnvVarProcessor to set defaults of other types than string in yaml configuration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
setting: '%env(int:default_value:123456789:EXAMPLE_NAME_OF_ENV_VARIABLE)%' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\DependencyInjection; | |
use Closure; | |
use Symfony\Component\DependencyInjection\EnvVarProcessorInterface; | |
use Symfony\Component\DependencyInjection\Exception\EnvNotFoundException; | |
/** | |
* Class EnvVarProcessor | |
* @package App\DependencyInjection | |
* | |
* @see https://symfony.com/doc/current/configuration/env_var_processors.html | |
*/ | |
class EnvVarProcessor implements EnvVarProcessorInterface | |
{ | |
/** | |
* @return string[] | |
*/ | |
public static function getProvidedTypes(): array | |
{ | |
return [ | |
'default_value' => 'bool|int|float|string|array', | |
]; | |
} | |
/** | |
* @inheritDoc | |
*/ | |
public function getEnv($prefix, $name, Closure $getEnv) | |
{ | |
if ('default_value' === $prefix) { | |
$i = strpos($name, ':'); | |
$default = substr($name, 0, $i); | |
$envName = substr($name, $i + 1); | |
try { | |
return $getEnv($envName); | |
} catch (EnvNotFoundException $exception) { | |
return $default; | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
services: | |
App\DependencyInjection\EnvVarProcessor: | |
tags: ['container.env_var_processor'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment