1. <?php
  2. /**
  3. * Streams date values for data migration with graceful failure handling.
  4. *
  5. * @param callable $date_provider A callable that returns an array of date values.
  6. * @param int $batch_size The number of date values to process in each batch.
  7. * @param callable $process_date A callable that processes a single date value.
  8. * @return void
  9. */
  10. function streamDatesForMigration(callable $date_provider, int $batch_size, callable $process_date): void
  11. {
  12. try {
  13. while (true) {
  14. $dates = $date_provider(); // Get a batch of dates
  15. if (empty($dates)) {
  16. break; // Stop if no more dates are available
  17. }
  18. foreach ($dates as $date) {
  19. try {
  20. $process_date($date); // Process each date
  21. } catch (\Exception $e) {
  22. // Handle individual date processing errors gracefully
  23. error_log("Error processing date: " . var_export($date, true) . ". Error: " . $e->getMessage());
  24. // Optionally, you can add retry logic here.
  25. }
  26. }
  27. }
  28. } catch (\Exception $e) {
  29. // Handle errors retrieving dates
  30. error_log("Error retrieving dates: " . $e->getMessage());
  31. }
  32. }
  33. // Example usage (replace with your actual date provider, processor, and batch size)
  34. /*
  35. function getDates(): array {
  36. // Simulate a date provider (e.g., reading from a file, database, API)
  37. $dates = [];
  38. for ($i = 0; $i < 10; $i++) {
  39. $dates[] = date("Y-m-d H:i:s", time() - $i);
  40. }
  41. return $dates;
  42. }
  43. function processDate(string $date): void {
  44. // Simulate date processing (e.g., data transformation, database insertion)
  45. echo "Processing date: " . $date . "\n";
  46. if ($date === "2024-01-01 12:00:00") {
  47. throw new \Exception("Simulated processing error");
  48. }
  49. }
  50. streamDatesForMigration(
  51. function () { return getDates(); },
  52. 2,
  53. function ($date) { processDate($date); }
  54. );
  55. */
  56. ?>

Add your comment