1. <?php
  2. function flattenConfig(array $config): array
  3. {
  4. $flattened = [];
  5. function recurse(array $current, string $prefix = '') use (&$flattened): void
  6. {
  7. foreach ($current as $key => $value) {
  8. $newKey = $prefix ? "$prefix.$key" : $key;
  9. if (is_array($value)) {
  10. recurse($value, $newKey);
  11. } else {
  12. $flattened[$newKey] = $value;
  13. }
  14. }
  15. }
  16. recurse($config);
  17. return $flattened;
  18. }
  19. function validateConfig(array $config): array
  20. {
  21. $errors = [];
  22. foreach ($config as $key => $value) {
  23. if (empty($value)) {
  24. $errors[$key] = "Value cannot be empty.";
  25. } elseif (is_string($value)) {
  26. if (strlen($value) > 255) {
  27. $errors[$key] = "String value exceeds maximum length (255 characters).";
  28. }
  29. } elseif (is_numeric($value)) {
  30. if ($value < 0) {
  31. $errors[$key] = "Numeric value cannot be negative.";
  32. }
  33. }
  34. }
  35. return $errors;
  36. }
  37. if (php_sapi_name() === 'cli') {
  38. // Example Usage (CLI)
  39. $config = [
  40. 'database' => [
  41. 'host' => 'localhost',
  42. 'port' => 3306,
  43. 'user' => 'root',
  44. 'password' => '', // Empty value for testing validation
  45. ],
  46. 'api' => [
  47. 'endpoint' => 'https://example.com/api',
  48. 'timeout' => 10,
  49. ],
  50. 'debug' => true,
  51. ];
  52. $flattenedConfig = flattenConfig($config);
  53. $validationErrors = validateConfig($flattenedConfig);
  54. if (empty($validationErrors)) {
  55. echo "Configuration is valid.\n";
  56. print_r($flattenedConfig);
  57. } else {
  58. echo "Validation errors:\n";
  59. print_r($validationErrors);
  60. }
  61. } else {
  62. // Example Usage (Web) - requires a config variable to be set.
  63. $config = [
  64. 'database' => [
  65. 'host' => 'localhost',
  66. 'port' => 3306,
  67. 'user' => 'root',
  68. 'password' => '', // Empty value for testing validation
  69. ],
  70. 'api' => [
  71. 'endpoint' => 'https://example.com/api',
  72. 'timeout' => 10,
  73. ],
  74. 'debug' => true,
  75. ];
  76. $flattenedConfig = flattenConfig($config);
  77. $validationErrors = validateConfig($flattenedConfig);
  78. if (empty($validationErrors)) {
  79. echo "Configuration is valid.\n";
  80. print_r($flattenedConfig);
  81. } else {
  82. echo "Validation errors:\n";
  83. print_r($validationErrors);
  84. }
  85. }
  86. ?>

Add your comment