Allow to override .env files per env

This commit is contained in:
Nicolas Grekas
2018-11-09 14:22:38 +01:00
parent 5b3ce90950
commit 95bb54353e
22 changed files with 157 additions and 90 deletions
@@ -5,7 +5,9 @@ namespace App;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\Console\Application;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Dotenv\Dotenv;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Routing\RouteCollectionBuilder;
@@ -58,4 +60,29 @@ class Kernel extends BaseKernel
$routes->import($confDir.'/{routes}/'.$this->environment.'/**/*'.self::CONFIG_EXTS, '/', 'glob');
$routes->import($confDir.'/{routes}'.self::CONFIG_EXTS, '/', 'glob');
}
public static function bootstrapCli(array &$argv)
{
// consume --env and --no-debug from the command line
Application::bootstrapEnv($argv);
}
public static function bootstrapEnv(string $env = null)
{
if (null !== $env) {
putenv('APP_ENV='.$_SERVER['APP_ENV'] = $env);
}
if ('prod' !== $_SERVER['APP_ENV'] = $_SERVER['APP_ENV'] ?? $_ENV['APP_ENV'] ?? null) {
if (!class_exists(Dotenv::class)) {
throw new \RuntimeException('The "APP_ENV" environment variable is not defined. You need to set it or run "composer require symfony/dotenv" to load it from a ".env" file.');
}
(new Dotenv())->loadEnv(\dirname(__DIR__).'/.env');
}
$_SERVER['APP_ENV'] = $_ENV['APP_ENV'] = $_SERVER['APP_ENV'] ?? $_SERVER['APP_ENV'] ?? 'dev';
$_SERVER['APP_DEBUG'] = $_SERVER['APP_DEBUG'] ?? $_ENV['APP_DEBUG'] ?? 'prod' !== $_SERVER['APP_ENV'];
$_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = (int) $_SERVER['APP_DEBUG'] || filter_var($_SERVER['APP_DEBUG'], FILTER_VALIDATE_BOOLEAN) ? '1' : '0';
}
}