Skip to content

Instantly share code, notes, and snippets.

@dennzo
Last active February 1, 2021 14:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dennzo/84f131aba2ed25262fffd74809788c99 to your computer and use it in GitHub Desktop.
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
setting: '%env(int:default_value:123456789:EXAMPLE_NAME_OF_ENV_VARIABLE)%'
<?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;
}
}
}
}
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