1. <?php
  2. /**
  3. * Parses configuration file arguments with defensive checks.
  4. *
  5. * @param array $args An array of command-line arguments.
  6. * @param array $defaultValues An array of default configuration values.
  7. * @return array An associative array representing the parsed configuration.
  8. * @throws InvalidArgumentException If an argument is missing or invalid.
  9. */
  10. function parseConfig(array $args, array $defaultValues): array
  11. {
  12. $config = $defaultValues;
  13. foreach ($args as $key => $value) {
  14. if (array_key_exists($key, $defaultValues)) {
  15. $defaultValue = $defaultValues[$key];
  16. // Defensive check: Ensure the value is not null or empty
  17. if ($value !== null && $value !== '') {
  18. $config[$key] = $value;
  19. }
  20. // else, keep the default value
  21. } else {
  22. // Argument not found
  23. throw new InvalidArgumentException("Missing configuration argument: " . $key);
  24. }
  25. }
  26. return $config;
  27. }
  28. /**
  29. * Example Usage - Demonstrate error handling and validation.
  30. */
  31. try {
  32. $arguments = ['--port' => '8080', '--debug' => 'true', '--log-file' => '/var/log/app.log'];
  33. $defaults = [
  34. 'port' => 80,
  35. 'debug' => false,
  36. 'log-file' => null,
  37. 'timeout' => 10,
  38. ];
  39. $config = parseConfig($arguments, $defaults);
  40. echo "<pre>";
  41. print_r($config);
  42. echo "</pre>";
  43. } catch (InvalidArgumentException $e) {
  44. echo "Error: " . $e->getMessage();
  45. }
  46. /**
  47. * Example Usage - Demonstrate missing argument handling.
  48. */
  49. try {
  50. $arguments = ['--port' => '8080']; //Missing debug
  51. $defaults = [
  52. 'port' => 80,
  53. 'debug' => false,
  54. ];
  55. $config = parseConfig($arguments, $defaults);
  56. echo "<pre>";
  57. print_r($config);
  58. echo "</pre>";
  59. } catch (InvalidArgumentException $e) {
  60. echo "Error: " . $e->getMessage();
  61. }
  62. ?>

Add your comment