From abd31e378517c452e5bb04694f2021de43274e2d Mon Sep 17 00:00:00 2001 From: Kevin Papst Date: Sat, 24 Oct 2020 21:00:43 +0200 Subject: [PATCH] allow to configure database version via ENV var (#2055) --- config/packages/doctrine.yaml | 3 +- .../Compiler/DoctrineCompilerPass.php | 48 +++++++++++-------- 2 files changed, 31 insertions(+), 20 deletions(-) diff --git a/config/packages/doctrine.yaml b/config/packages/doctrine.yaml index d169b44c..1811eba4 100644 --- a/config/packages/doctrine.yaml +++ b/config/packages/doctrine.yaml @@ -4,6 +4,7 @@ parameters: # environment variables are not available yet. # You should not need to change this value. env(DATABASE_URL): '' + env(DATABASE_VERSION): ~ doctrine: dbal: @@ -14,7 +15,7 @@ doctrine: driver: 'pdo_mysql' # this setting prevents automatic database detection and finds a lot of false-negatives on doctrine:migrations:diff # for null columns with MariaDB. Each migration tries to convert EVERY nullable column. - # server_version: '5.7' + server_version: '%env(string:DATABASE_VERSION)%' charset: utf8mb4 default_table_options: charset: utf8mb4 diff --git a/src/DependencyInjection/Compiler/DoctrineCompilerPass.php b/src/DependencyInjection/Compiler/DoctrineCompilerPass.php index b0253e38..1a56caf7 100644 --- a/src/DependencyInjection/Compiler/DoctrineCompilerPass.php +++ b/src/DependencyInjection/Compiler/DoctrineCompilerPass.php @@ -26,37 +26,47 @@ class DoctrineCompilerPass implements CompilerPassInterface 'sqlite' ]; + private function getEnvVar(string $name): ?string + { + $envVarValue = null; + + if (isset($_ENV[$name])) { + $envVarValue = $_ENV[$name]; + } + + if ($envVarValue === null && isset($_SERVER[$name])) { + $envVarValue = $_SERVER[$name]; + } + + if ($envVarValue === null) { + $envVarValue = getenv($name); + } + + if ($envVarValue === false || empty($envVarValue)) { + return null; + } + + return $envVarValue; + } + /** - * @return array|false|null|string + * @return string * @throws \Exception */ - protected function findEngine() + private function findEngine(): string { $engine = null; - $databaseUrl = null; - if (null === $databaseUrl && isset($_ENV['DATABASE_URL'])) { - $databaseUrl = $_ENV['DATABASE_URL']; - } - - if (null === $databaseUrl && isset($_SERVER['DATABASE_URL'])) { - $databaseUrl = $_SERVER['DATABASE_URL']; - } - - if (null === $databaseUrl && (false !== $envDbUrl = getenv('DATABASE_URL'))) { - $databaseUrl = $envDbUrl; - } - - if (null !== $databaseUrl) { + if (null !== ($databaseUrl = $this->getEnvVar('DATABASE_URL'))) { $urlParts = explode('://', $databaseUrl); $engine = $urlParts[0] ?: null; } - if (null === $engine) { - $engine = getenv('DATABASE_ENGINE'); + if ($engine === null) { + $engine = $this->getEnvVar('DATABASE_ENGINE'); } - if (empty($engine)) { + if ($engine === null) { throw new \Exception( 'Could not detect database engine, make sure DATABASE_URL is available from $_SERVER or $_ENV. Check your .env file.' );