1. <?php
  2. /**
  3. * Compares JSON responses with a configuration file.
  4. *
  5. * @param string $jsonResponse The JSON response string to compare.
  6. * @param string $configFilePath Path to the configuration file (JSON).
  7. * @return array An array of differences found, or an empty array if no differences.
  8. */
  9. function compareJsonWithConfig(string $jsonResponse, string $configFilePath): array
  10. {
  11. // Decode the JSON response
  12. $response = json_decode($jsonResponse, true);
  13. if ($response === null) {
  14. return ['error' => 'Invalid JSON response']; // Handle invalid JSON
  15. }
  16. // Decode the configuration file
  17. $config = json_decode(file_get_contents($configFilePath), true);
  18. if ($config === null) {
  19. return ['error' => 'Invalid JSON configuration file'];
  20. }
  21. $differences = [];
  22. // Compare the top-level keys
  23. foreach (array_keys($response) as $key) {
  24. if (!array_key_exists($key, $config)) {
  25. $differences[] = ['key' => $key, 'message' => 'Key missing in configuration'];
  26. continue;
  27. }
  28. if (!is_array($response[$key]) && !is_array($config[$key])) {
  29. if ($response[$key] !== $config[$key]) {
  30. $differences[] = ['key' => $key, 'response' => $response[$key], 'config' => $config[$key], 'message' => 'Value mismatch'];
  31. }
  32. } elseif (is_array($response[$key]) && is_array($config[$key])) {
  33. $arrayDifferences = array_diff($response[$key], $config[$key]);
  34. if (!empty($arrayDifferences)) {
  35. $differences[] = ['key' => $key, 'message' => 'Array differences found', 'arrayDifferences' => $arrayDifferences];
  36. }
  37. } else {
  38. if ($response[$key] !== $config[$key]) {
  39. $differences[] = ['key' => $key, 'response' => $response[$key], 'config' => $config[$key], 'message' => 'Value mismatch'];
  40. }
  41. }
  42. }
  43. return $differences;
  44. }
  45. //Example Usage
  46. /*
  47. $jsonResponse = '{
  48. "name": "John Doe",
  49. "age": 30,
  50. "city": "New York",
  51. "hobbies": ["reading", "hiking"]
  52. }';
  53. $configFilePath = 'config.json'; // Create a config.json file
  54. $differences = compareJsonWithConfig($jsonResponse, $configFilePath);
  55. if (empty($differences)) {
  56. echo "No differences found.\n";
  57. } else {
  58. echo "Differences found:\n";
  59. print_r($differences);
  60. }
  61. */
  62. ?>

Add your comment