1. <?php
  2. /**
  3. * Normalizes environment variables for staging environments with dry-run mode.
  4. *
  5. * @param array $envVars An array of environment variables to normalize.
  6. * @param bool $dryRun Whether to only output the changes, not apply them.
  7. * @return array Normalized environment variables.
  8. */
  9. function normalizeEnvVars(array $envVars, bool $dryRun = false): array
  10. {
  11. $normalizedVars = [];
  12. foreach ($envVars as $key => $value) {
  13. // Normalize key to snake_case
  14. $normalizedKey = preg_replace('/(?<!^)(?=[A-Z])/', '_', strtolower($key));
  15. // Apply specific staging environment defaults/rules
  16. if ($normalizedKey === 'DATABASE_URL') {
  17. if ($dryRun) {
  18. echo "DRY RUN: Normalizing DATABASE_URL to staging_db_url\n";
  19. }
  20. $normalizedVars[$normalizedKey] = $_ENV['STAGING_DATABASE_URL'] ?? 'staging_db_url'; //Use STAGING_DATABASE_URL if defined, otherwise a default
  21. } elseif ($normalizedKey === 'API_KEY') {
  22. if ($dryRun) {
  23. echo "DRY RUN: Normalizing API_KEY to staging_api_key\n";
  24. }
  25. $normalizedVars[$normalizedKey] = $_ENV['STAGING_API_KEY'] ?? 'staging_api_key';
  26. } elseif ($normalizedKey === 'DEBUG') {
  27. if ($dryRun) {
  28. echo "DRY RUN: Normalizing DEBUG to false\n";
  29. }
  30. $normalizedVars[$normalizedKey] = false;
  31. } else {
  32. $normalizedVars[$normalizedKey] = $value; //Keep original value if no normalization needed
  33. }
  34. }
  35. if ($dryRun) {
  36. echo "DRY RUN: Would apply the following changes:\n";
  37. print_r($normalizedVars);
  38. } else {
  39. //Apply the normalized environment variables to the $_ENV superglobal
  40. foreach ($normalizedVars as $key => $value) {
  41. putenv($key . "=" . $value);
  42. }
  43. }
  44. return $normalizedVars;
  45. }
  46. //Example usage:
  47. // $envVars = [
  48. // 'DatabaseUrl' => 'Production_db_url',
  49. // 'APIKey' => 'Production_apiKey',
  50. // 'Debug' => 'true',
  51. // ];
  52. // $normalized = normalizeEnvVars($envVars, true); //Dry run
  53. // print_r($normalized);
  54. // normalizeEnvVars($envVars); //Apply changes
  55. ?>

Add your comment