<?php
function flattenConfig(array $config): array
{
$flattened = [];
function recurse(array $current, string $prefix = '') use (&$flattened): void
{
foreach ($current as $key => $value) {
$newKey = $prefix ? "$prefix.$key" : $key;
if (is_array($value)) {
recurse($value, $newKey);
} else {
$flattened[$newKey] = $value;
}
}
}
recurse($config);
return $flattened;
}
function validateConfig(array $config): array
{
$errors = [];
foreach ($config as $key => $value) {
if (empty($value)) {
$errors[$key] = "Value cannot be empty.";
} elseif (is_string($value)) {
if (strlen($value) > 255) {
$errors[$key] = "String value exceeds maximum length (255 characters).";
}
} elseif (is_numeric($value)) {
if ($value < 0) {
$errors[$key] = "Numeric value cannot be negative.";
}
}
}
return $errors;
}
if (php_sapi_name() === 'cli') {
// Example Usage (CLI)
$config = [
'database' => [
'host' => 'localhost',
'port' => 3306,
'user' => 'root',
'password' => '', // Empty value for testing validation
],
'api' => [
'endpoint' => 'https://example.com/api',
'timeout' => 10,
],
'debug' => true,
];
$flattenedConfig = flattenConfig($config);
$validationErrors = validateConfig($flattenedConfig);
if (empty($validationErrors)) {
echo "Configuration is valid.\n";
print_r($flattenedConfig);
} else {
echo "Validation errors:\n";
print_r($validationErrors);
}
} else {
// Example Usage (Web) - requires a config variable to be set.
$config = [
'database' => [
'host' => 'localhost',
'port' => 3306,
'user' => 'root',
'password' => '', // Empty value for testing validation
],
'api' => [
'endpoint' => 'https://example.com/api',
'timeout' => 10,
],
'debug' => true,
];
$flattenedConfig = flattenConfig($config);
$validationErrors = validateConfig($flattenedConfig);
if (empty($validationErrors)) {
echo "Configuration is valid.\n";
print_r($flattenedConfig);
} else {
echo "Validation errors:\n";
print_r($validationErrors);
}
}
?>
Add your comment