1. <?php
  2. /**
  3. * Compresses configuration files for a quick prototype.
  4. * Handles potential errors gracefully.
  5. *
  6. * @param array $config_array An associative array representing the configuration.
  7. * @param string $output_file The path to the output file.
  8. * @return bool True on success, false on failure.
  9. */
  10. function compactConfig(array $config_array, string $output_file): bool
  11. {
  12. try {
  13. $compacted_config = [];
  14. foreach ($config_array as $key => $value) {
  15. // Handle different data types
  16. if (is_array($value)) {
  17. $compacted_config[$key] = compactConfig($value, 'nested_' . $key); // Recursive call for nested arrays
  18. } else {
  19. $compacted_config[$key] = $value;
  20. }
  21. }
  22. // Output to file
  23. file_put_contents($output_file, json_encode($compacted_config, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); // Use JSON for compact representation
  24. return true;
  25. } catch (Exception $e) {
  26. error_log("Error compacting config: " . $e->getMessage()); // Log errors
  27. return false;
  28. }
  29. }
  30. //Example Usage (for testing)
  31. /*
  32. $config = [
  33. 'database' => [
  34. 'host' => 'localhost',
  35. 'user' => 'admin',
  36. 'password' => 'password',
  37. ],
  38. 'api' => [
  39. 'url' => 'https://api.example.com',
  40. 'timeout' => 10,
  41. ],
  42. 'debug' => true,
  43. 'nested_array' => [ 1 => 'value1', 2 => 'value2' ],
  44. ];
  45. $output_file = 'compacted_config.json';
  46. if (compactConfig($config, $output_file)) {
  47. echo "Configuration compacted to " . $output_file . "\n";
  48. } else {
  49. echo "Configuration compacting failed.\n";
  50. }
  51. */
  52. ?>

Add your comment