{"record":{"id":"3ccb52a997052564","repo":"vlucas/phpdotenv","slug":"one-or-more-environment-variables-failed-assertion","errorCode":null,"errorMessage":"One or more environment variables failed assertions: %s.","messagePattern":"One or more environment variables failed assertions: (.+?)\\.","errorType":"validation","errorClass":"ValidationException","httpStatus":null,"severity":"critical","filePath":"src/Validator.php","lineNumber":173,"sourceCode":"     * @param callable(?string):bool $callback\n     * @param string                 $message\n     *\n     * @throws \\Dotenv\\Exception\\ValidationException\n     *\n     * @return \\Dotenv\\Validator\n     */\n    public function assert(callable $callback, string $message)\n    {\n        $failing = [];\n\n        foreach ($this->variables as $variable) {\n            if ($callback($this->repository->get($variable)) === false) {\n                $failing[] = \\sprintf('%s %s', $variable, $message);\n            }\n        }\n\n        if (\\count($failing) > 0) {\n            throw new ValidationException(\\sprintf(\n                'One or more environment variables failed assertions: %s.',\n                \\implode(', ', $failing)\n            ));\n        }\n\n        return $this;\n    }\n\n    /**\n     * Assert that the callback returns true for each variable.\n     *\n     * Skip checking null variable values.\n     *\n     * @param callable(string):bool $callback\n     * @param string                $message\n     *\n     * @throws \\Dotenv\\Exception\\ValidationException\n     *","sourceCodeStart":155,"sourceCodeEnd":191,"githubUrl":"https://github.com/vlucas/phpdotenv/blob/416df702837983f8d5ff48c9c3fee4f5f57b980b/src/Validator.php#L155-L191","documentation":"Validator::assert() (src/Validator.php:173) is the funnel behind required(), notEmpty(), isInteger(), isBoolean(), allowedValues(), allowedRegexValues() and custom assertions: it evaluates a callback per variable against the repository and, if any returned false, aggregates 'VAR <reason>' fragments (e.g. 'DB_HOST is missing', 'PORT is not an integer') and throws Dotenv\\Exception\\ValidationException. One exception therefore reports every failing variable at once. required() itself is just assert(fn ($v) => $v !== null, 'is missing'), and assertNullable-based checks skip variables whose value is null.","triggerScenarios":"Dotenv::createImmutable($dir)->load()->required('DB_HOST') when DB_HOST is absent (-> 'DB_HOST is missing'); ->required('APP_KEY')->notEmpty() when APP_KEY is unset, '' or whitespace-only (notEmpty trims before checking); ->required('PORT')->isInteger() with PORT=8080.5; allowedValues(['staging','prod']) with APP_ENV=dev; calling ->required() after safeLoad() when no file was read at all.","commonSituations":"New deploy/container missing secrets; fresh clone without .env; typo in the required() list ('DB_H0ST'); vars defined in .env but a different file was loaded (wrong path/name); whitespace-only values from a template; CI runners lacking environment configuration.","solutions":["Read the message — it lists each failing variable with its reason; fix those entries in .env or the real environment first.","Check spelling of the variable names in required([...]) against the .env keys.","Make optional variables non-fatal with ifPresent([...])->notEmpty() instead of required(...).","Allow empty values where legitimate: stop at ->required() and drop ->notEmpty().","For guided setup, catch the exception and print 'copy .env.example to .env and fill it in', exiting non-zero."],"exampleFix":"// before\n$dotenv->required(['APP_KEY', 'DB_HOST', 'MAIL_FROM'])->notEmpty();\n\n// after\n$dotenv->required(['APP_KEY', 'DB_HOST'])->notEmpty(); // hard dependencies\n$dotenv->ifPresent(['MAIL_FROM'])->notEmpty();          // optional but must not be blank when set","handlingStrategy":"try-catch","validationCode":"// Quick pre-boot presence check for hard dependencies (mirrors required()):\n$required = ['APP_KEY', 'DB_HOST'];\n$missing = array_filter(\n    $required,\n    static fn (string $name): bool => $_ENV[$name] ?? getenv($name) === false\n);\nif ($missing !== []) {\n    fwrite(STDERR, 'Missing env vars: ' . implode(', ', $missing) . \\PHP_EOL);\n    exit(1);\n}","typeGuard":null,"tryCatchPattern":"use Dotenv\\Exception\\ValidationException;\n\ntry {\n    $dotenv->required(['APP_KEY', 'DB_HOST'])->notEmpty();\n} catch (ValidationException $e) {\n    // message already lists every failing var and reason, e.g.\n    // 'One or more environment variables failed assertions: APP_KEY is missing, DB_HOST is empty.'\n    fwrite(STDERR, $e->getMessage() . \\PHP_EOL . 'Hint: copy .env.example to .env and fill it in.' . \\PHP_EOL);\n    exit(1); // fail the boot/deploy instead of running half-configured\n}","preventionTips":["Keep .env.example as the source of truth and diff it against .env in CI.","Prefer ifPresent() for optional variables so absent values do not kill boot.","Run the full required()/notEmpty() chain in a deploy smoke test before traffic switches.","Watch for required()-list typos — a misspelled name reports as 'is missing' even though the real var is set."],"tags":["dotenv","validation","env-var","configuration","php"],"backgroundTag":"missing-env-var","analyzedSha":"416df702837983f8d5ff48c9c3fee4f5f57b980b","analyzedAt":"2026-08-21T01:19:52.946Z","schemaVersion":2},"datasetVersion":"2026-08-21T03:17:12.404Z"}