Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Detect unused environment variables in .env #48552

Closed
@GromNaN

Description

@GromNaN

Description

During the life of a Symfony project, we add new environment variables when needed and sometime we forget to remove environment variables from the .env files when they are no longer necessary.

I think we could detect which env var is used when the container is built and compare with the env var that are loaded from .env and listed in SYMFONY_DOTENV_VARS.

There would be an allow list (APP_ENV, APP_DEBUG, LOG_LEVEL). But if a variable is used in the code using superglobal but not in the config, there would be false positive (unless the allow list is configurable).

This is also a good way to promote best practices: using DI config instead of direct access to $_SERVER or $_ENV.

There is a similar mechanism in PhpDumper, but it only detects when an environment variable is used in the config but the value is not passed to the container build.

$unusedEnvs = [];
foreach ($this->container->getEnvCounters() as $env => $use) {
if (!$use) {
$unusedEnvs[] = $env;
}
}
if ($unusedEnvs) {
throw new EnvParameterException($unusedEnvs, null, 'Environment variables "%s" are never used. Please, check your container\'s configuration.');
}

Example

UNUSED_VAR=test
$ bin/console cache:clear

 // Clearing the cache for the dev environment with debug true

 // Clearing outdated warmup directory...

 // Warming up cache...

16:25:41 WARNING     Environment variable "UNUSED_VAR" is declared in the .env file but never used in the configuration.

 // Removing old build and cache directory...

 // Finished


 [OK] Cache for the "dev" environment (debug=true) was successfully cleared.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions