Search code examples
phpsymfonyphp-7dotenvphpdotenv

Symfony 5.1.8 ignoring overrides from .env.test / .env.test.local


I have a Symfony 5.1.8 project, in which I want to use a different database connection for testing. To do so, I set up the file .env.test.local with a different value for DATABASE_URL than in my .env.local, just like the documentation in the .env file states:

# In all environments, the following files are loaded if they exist,
# the latter taking precedence over the former:
#
#  * .env.local                contains default values for the environment variables needed by the app
#  * .env.local.local          uncommitted file with local overrides
#  * .env.local.$APP_ENV       committed environment-specific defaults
#  * .env.local.$APP_ENV.local uncommitted environment-specific overrides
#
# Real environment variables win over .env.local files.

Symfony seems to ignore these overrides and always uses the values provided in .env.local.

To find out what exactly happens I changed the last line in bin/console from $application->run($input); to dd($_ENV); in order to just dump whatever environment variables symfony sees during its execution.

Here are the contents of my different .env files:

.env

APP_ENV=dev
ENV_VAR=ENV

.env.local

APP_ENV=dev
ENV_VAR=ENV_LOCAL

.env.test

APP_ENV=test
ENV_VAR=ENV_TEST

.env.test.local

APP_ENV=test
ENV_VAR=ENV_TEST_LOCAL

When I run php bin/console now the output is as follows:

array:10 [
  "APP_ENV" => "dev"
  "ENV_VAR" => "ENV_LOCAL"
  ...
]

Which is what I expect. But when I run php bin/console -e test the following is being printed:

array:10 [
  "APP_ENV" => "test"
  "ENV_VAR" => "ENV_LOCAL"
  ...
]

APP_ENV is set correctly, according to the -e parameter, but still, for ENV_VAR the value from .env.local is taken.

Do I have a misconception about the .env-files and their behaviour or is this a bug of some sort?

In case it matters, I am currently working on Windows 10 with PHP 7.3.24.


Solution

  • It was a configuration error on my side.

    When I first started this project I did not fully grasp the concept of multi level .env files and did a little change to the bin/console executable, to make things "easier" for me:

    curl -o console.temp https://raw.githubusercontent.com/symfony/recipes/master/symfony/console/5.1/bin/console
    diff console console.temp
    31c31
    < (new Dotenv())->bootEnv(dirname(__DIR__) . '/.env.local');
    ---
    > (new Dotenv())->bootEnv(dirname(__DIR__).'/.env');
    

    This, of course prevented the whole DotEnv thingy from working correctly. I just forgot about this change that I introduced, but thanks to @PierrickM's comment on my question, everything is working fine now!