1. <?php
  2. /**
  3. * Mirrors data of entries with basic sanity checks for manual execution.
  4. *
  5. * @param array $sourceData Array of source data entries.
  6. * @param array $destinationData Array of destination data entries.
  7. * @param array $checkFields Array of fields to perform sanity checks on.
  8. * @return array Array of updated destination data entries.
  9. */
  10. function mirrorData(array $sourceData, array $destinationData, array $checkFields): array
  11. {
  12. $updatedData = [];
  13. foreach ($sourceData as $sourceEntry) {
  14. $matchingEntry = null;
  15. foreach ($destinationData as $destEntry) {
  16. // Match based on a common identifier (e.g., ID)
  17. if (isset($sourceEntry['id']) && isset($destEntry['id']) && $sourceEntry['id'] == $destEntry['id']) {
  18. $matchingEntry = $destEntry;
  19. break;
  20. }
  21. }
  22. if ($matchingEntry !== null) {
  23. // Mirror the data, performing sanity checks
  24. $updatedEntry = $matchingEntry;
  25. foreach ($checkFields as $field) {
  26. if (isset($sourceEntry[$field]) && isset($matchingEntry[$field]) && $sourceEntry[$field] !== $matchingEntry[$field]) {
  27. // Sanity check: Data mismatch
  28. error_log("Sanity check failed for field: " . $field . " - Source: " . $sourceEntry[$field] . ", Destination: " . $matchingEntry[$field]);
  29. // Optionally, handle the mismatch (e.g., log, skip, alert)
  30. // For now, we'll just leave the data as is.
  31. }
  32. }
  33. $updatedData[] = $updatedEntry;
  34. } else {
  35. // No matching entry found in destination data
  36. error_log("No matching entry found in destination data for ID: " . (isset($sourceEntry['id']) ? $sourceEntry['id'] : 'N/A'));
  37. $updatedData[] = $sourceEntry; // Keep the source entry
  38. }
  39. }
  40. return $updatedData;
  41. }
  42. // Example Usage (for manual execution)
  43. /*
  44. $sourceData = [
  45. ['id' => 1, 'name' => 'Alice', 'email' => 'alice@example.com', 'age' => 30],
  46. ['id' => 2, 'name' => 'Bob', 'email' => 'bob@example.com', 'age' => 25],
  47. ['id' => 3, 'name' => 'Charlie', 'email' => 'charlie@example.com', 'age' => 40],
  48. ];
  49. $destinationData = [
  50. ['id' => 1, 'name' => 'Alice', 'email' => 'alice@example.com', 'age' => 30],
  51. ['id' => 2, 'name' => 'Robert', 'email' => 'robert@example.com', 'age' => 26], // Different name and age
  52. ];
  53. $checkFields = ['name', 'email', 'age'];
  54. $updatedData = mirrorData($sourceData, $destinationData, $checkFields);
  55. // Output the updated data (for manual inspection)
  56. print_r($updatedData);
  57. */
  58. ?>

Add your comment