<?php
/**
* Compares JSON responses with a configuration file.
*
* @param string $jsonResponse The JSON response string to compare.
* @param string $configFilePath Path to the configuration file (JSON).
* @return array An array of differences found, or an empty array if no differences.
*/
function compareJsonWithConfig(string $jsonResponse, string $configFilePath): array
{
// Decode the JSON response
$response = json_decode($jsonResponse, true);
if ($response === null) {
return ['error' => 'Invalid JSON response']; // Handle invalid JSON
}
// Decode the configuration file
$config = json_decode(file_get_contents($configFilePath), true);
if ($config === null) {
return ['error' => 'Invalid JSON configuration file'];
}
$differences = [];
// Compare the top-level keys
foreach (array_keys($response) as $key) {
if (!array_key_exists($key, $config)) {
$differences[] = ['key' => $key, 'message' => 'Key missing in configuration'];
continue;
}
if (!is_array($response[$key]) && !is_array($config[$key])) {
if ($response[$key] !== $config[$key]) {
$differences[] = ['key' => $key, 'response' => $response[$key], 'config' => $config[$key], 'message' => 'Value mismatch'];
}
} elseif (is_array($response[$key]) && is_array($config[$key])) {
$arrayDifferences = array_diff($response[$key], $config[$key]);
if (!empty($arrayDifferences)) {
$differences[] = ['key' => $key, 'message' => 'Array differences found', 'arrayDifferences' => $arrayDifferences];
}
} else {
if ($response[$key] !== $config[$key]) {
$differences[] = ['key' => $key, 'response' => $response[$key], 'config' => $config[$key], 'message' => 'Value mismatch'];
}
}
}
return $differences;
}
//Example Usage
/*
$jsonResponse = '{
"name": "John Doe",
"age": 30,
"city": "New York",
"hobbies": ["reading", "hiking"]
}';
$configFilePath = 'config.json'; // Create a config.json file
$differences = compareJsonWithConfig($jsonResponse, $configFilePath);
if (empty($differences)) {
echo "No differences found.\n";
} else {
echo "Differences found:\n";
print_r($differences);
}
*/
?>
Add your comment