Files
D1041231009-WebGIS-SPBU/docker/sync-env.php
T
2026-06-11 14:53:35 +07:00

102 lines
2.3 KiB
PHP

<?php
declare(strict_types=1);
function docker_sync_env_keys(): array
{
return [
'APP_NAME',
'APP_ENV',
'APP_KEY',
'APP_DEBUG',
'APP_URL',
'DB_CONNECTION',
'DB_HOST',
'DB_PORT',
'DB_DATABASE',
'DB_USERNAME',
'DB_PASSWORD',
'SESSION_DRIVER',
'CACHE_STORE',
'QUEUE_CONNECTION',
];
}
function docker_sync_env_format_value(string $value): string
{
if ($value === '') {
return '';
}
if (preg_match('/\A[A-Za-z0-9_\.\/:@+\-]+\z/', $value) === 1) {
return $value;
}
$escaped = str_replace(
["\\", "\"", "\n", "\r"],
["\\\\", "\\\"", "\\n", ''],
$value
);
return "\"{$escaped}\"";
}
function docker_sync_env_file(string $path, array $keys, ?array $values = null): void
{
$lines = file_exists($path) ? file($path, FILE_IGNORE_NEW_LINES) : [];
if ($lines === false) {
throw new RuntimeException("Unable to read {$path}.");
}
$updates = [];
foreach ($keys as $key) {
$value = $values === null ? getenv($key) : ($values[$key] ?? false);
if ($value === false) {
continue;
}
$updates[$key] = docker_sync_env_format_value((string) $value);
}
if ($updates === []) {
return;
}
$seen = [];
foreach ($lines as $index => $line) {
foreach ($updates as $key => $value) {
if (preg_match('/^\s*'.preg_quote($key, '/').'=/i', $line) === 1) {
$lines[$index] = "{$key}={$value}";
$seen[$key] = true;
break;
}
}
}
foreach ($updates as $key => $value) {
if (! isset($seen[$key])) {
$lines[] = "{$key}={$value}";
}
}
$content = implode(PHP_EOL, $lines).PHP_EOL;
if (file_put_contents($path, $content) === false) {
throw new RuntimeException("Unable to write {$path}.");
}
}
$script = isset($_SERVER['SCRIPT_FILENAME']) ? realpath($_SERVER['SCRIPT_FILENAME']) : false;
if ($script !== false && $script === realpath(__FILE__)) {
$path = $argv[1] ?? dirname(__DIR__).'/.env';
docker_sync_env_file($path, docker_sync_env_keys());
fwrite(STDOUT, "Docker environment synchronized into .env.\n");
}