1. <?php
  2. /**
  3. * Batch Operations with Graceful Failure Handling
  4. *
  5. * This function processes a list of entries in batches, handling errors gracefully
  6. * and logging them.
  7. *
  8. * @param array $entries An array of entries to process. Each entry should be an associative array.
  9. * @param int $batch_size The number of entries to process in each batch.
  10. * @param callable $operation A callable (function) that takes an entry as input and performs the operation.
  11. * @param callable|null $error_handler An optional callable to handle errors. If null, errors are logged.
  12. * @return array An array of results, where each result corresponds to an entry. Returns an array of errors if something goes wrong.
  13. */
  14. function batch_operations(array $entries, int $batch_size, callable $operation, ?callable $error_handler = null): array
  15. {
  16. $results = [];
  17. $errors = [];
  18. if (empty($entries)) {
  19. return $results; // Return empty array if no entries
  20. }
  21. for ($i = 0; $i < count($entries); $i += $batch_size) {
  22. $batch = array_slice($entries, $i, $batch_size);
  23. foreach ($batch as $entry) {
  24. try {
  25. $result = $operation($entry);
  26. $results[] = $result; // Store the result
  27. } catch (\Exception $e) {
  28. $error_message = "Error processing entry: " . json_encode($entry) . "\n" . $e->getMessage();
  29. if ($error_handler) {
  30. $error_handler($error_message, $entry); // Use custom error handler
  31. } else {
  32. $errors[] = ['entry' => $entry, 'error' => $error_message]; // Log error
  33. }
  34. }
  35. }
  36. }
  37. if (!empty($errors)) {
  38. return $errors; // Return errors if any
  39. }
  40. return $results;
  41. }
  42. // Example Usage (demonstration)
  43. /*
  44. // Sample operation (replace with your actual operation)
  45. function process_entry(array $entry): string
  46. {
  47. // Simulate an error sometimes
  48. if (rand(0, 10) < 2) {
  49. throw new \Exception("Simulated error!");
  50. }
  51. return "Processed: " . $entry['id'];
  52. }
  53. // Example error handler
  54. function my_error_handler($message, $entry) {
  55. error_log("Custom Error: " . $message);
  56. }
  57. $entries = [
  58. ['id' => 1, 'data' => 'value1'],
  59. ['id' => 2, 'data' => 'value2'],
  60. ['id' => 3, 'data' => 'value3'],
  61. ['id' => 4, 'data' => 'value4'],
  62. ['id' => 5, 'data' => 'value5'],
  63. ];
  64. $batch_size = 2;
  65. $results = batch_operations($entries, $batch_size, 'process_entry', [$my_error_handler]);
  66. if (empty($results)) {
  67. echo "All entries processed successfully.\n";
  68. } else {
  69. echo "Errors occurred during processing:\n";
  70. print_r($results);
  71. }
  72. */
  73. ?>

Add your comment