vlucas / phpdotenv

Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SERVER` automagically.
BSD 3-Clause "New" or "Revised" License
13.15k stars 626 forks source link

One or more environment variables failed assertions: ... #524

Closed OnkelTem closed 2 years ago

OnkelTem commented 2 years ago

I use a third-party project which fails to run, because it cannot find variables from my .env file.

One or more environment variables failed assertions: WPC_DB_HOST is missing, \
WPC_DB_NAME is missing, WPC_DB_USER is missing, WPC_DB_PASSWORD is missing.

I found this code:

$dotenv = Dotenv::createImmutable( __DIR__ . '/../' );
$dotenv->required( [ 'WPC_DB_HOST', 'WPC_DB_NAME', 'WPC_DB_USER', 'WPC_DB_PASSWORD' ] ); // Throws here!
$dotenv->ifPresent( 'ALLOW_INSECURE' )->isBoolean();
$dotenv->load();

which raises exception in the second line, so the load() method has no chance to be called.

I wonder how it was supposed to work?

GrahamCampbell commented 2 years ago

That's correct. You need to move your validation to after the call to load. The validation immediately performs assertions about the current state of your environment, not about the env file. :)

OnkelTem commented 2 years ago

Hehe, I can't imagine how it worked in the original code :)