<?php
/**
* Parses configuration file arguments with defensive checks.
*
* @param array $args An array of command-line arguments.
* @param array $defaultValues An array of default configuration values.
* @return array An associative array representing the parsed configuration.
* @throws InvalidArgumentException If an argument is missing or invalid.
*/
function parseConfig(array $args, array $defaultValues): array
{
$config = $defaultValues;
foreach ($args as $key => $value) {
if (array_key_exists($key, $defaultValues)) {
$defaultValue = $defaultValues[$key];
// Defensive check: Ensure the value is not null or empty
if ($value !== null && $value !== '') {
$config[$key] = $value;
}
// else, keep the default value
} else {
// Argument not found
throw new InvalidArgumentException("Missing configuration argument: " . $key);
}
}
return $config;
}
/**
* Example Usage - Demonstrate error handling and validation.
*/
try {
$arguments = ['--port' => '8080', '--debug' => 'true', '--log-file' => '/var/log/app.log'];
$defaults = [
'port' => 80,
'debug' => false,
'log-file' => null,
'timeout' => 10,
];
$config = parseConfig($arguments, $defaults);
echo "<pre>";
print_r($config);
echo "</pre>";
} catch (InvalidArgumentException $e) {
echo "Error: " . $e->getMessage();
}
/**
* Example Usage - Demonstrate missing argument handling.
*/
try {
$arguments = ['--port' => '8080']; //Missing debug
$defaults = [
'port' => 80,
'debug' => false,
];
$config = parseConfig($arguments, $defaults);
echo "<pre>";
print_r($config);
echo "</pre>";
} catch (InvalidArgumentException $e) {
echo "Error: " . $e->getMessage();
}
?>
Add your comment