<?php
/**
* Normalizes environment variables for staging environments with dry-run mode.
*
* @param array $envVars An array of environment variables to normalize.
* @param bool $dryRun Whether to only output the changes, not apply them.
* @return array Normalized environment variables.
*/
function normalizeEnvVars(array $envVars, bool $dryRun = false): array
{
$normalizedVars = [];
foreach ($envVars as $key => $value) {
// Normalize key to snake_case
$normalizedKey = preg_replace('/(?<!^)(?=[A-Z])/', '_', strtolower($key));
// Apply specific staging environment defaults/rules
if ($normalizedKey === 'DATABASE_URL') {
if ($dryRun) {
echo "DRY RUN: Normalizing DATABASE_URL to staging_db_url\n";
}
$normalizedVars[$normalizedKey] = $_ENV['STAGING_DATABASE_URL'] ?? 'staging_db_url'; //Use STAGING_DATABASE_URL if defined, otherwise a default
} elseif ($normalizedKey === 'API_KEY') {
if ($dryRun) {
echo "DRY RUN: Normalizing API_KEY to staging_api_key\n";
}
$normalizedVars[$normalizedKey] = $_ENV['STAGING_API_KEY'] ?? 'staging_api_key';
} elseif ($normalizedKey === 'DEBUG') {
if ($dryRun) {
echo "DRY RUN: Normalizing DEBUG to false\n";
}
$normalizedVars[$normalizedKey] = false;
} else {
$normalizedVars[$normalizedKey] = $value; //Keep original value if no normalization needed
}
}
if ($dryRun) {
echo "DRY RUN: Would apply the following changes:\n";
print_r($normalizedVars);
} else {
//Apply the normalized environment variables to the $_ENV superglobal
foreach ($normalizedVars as $key => $value) {
putenv($key . "=" . $value);
}
}
return $normalizedVars;
}
//Example usage:
// $envVars = [
// 'DatabaseUrl' => 'Production_db_url',
// 'APIKey' => 'Production_apiKey',
// 'Debug' => 'true',
// ];
// $normalized = normalizeEnvVars($envVars, true); //Dry run
// print_r($normalized);
// normalizeEnvVars($envVars); //Apply changes
?>
Add your comment