<?php
/**
* Batch Operations with Graceful Failure Handling
*
* This function processes a list of entries in batches, handling errors gracefully
* and logging them.
*
* @param array $entries An array of entries to process. Each entry should be an associative array.
* @param int $batch_size The number of entries to process in each batch.
* @param callable $operation A callable (function) that takes an entry as input and performs the operation.
* @param callable|null $error_handler An optional callable to handle errors. If null, errors are logged.
* @return array An array of results, where each result corresponds to an entry. Returns an array of errors if something goes wrong.
*/
function batch_operations(array $entries, int $batch_size, callable $operation, ?callable $error_handler = null): array
{
$results = [];
$errors = [];
if (empty($entries)) {
return $results; // Return empty array if no entries
}
for ($i = 0; $i < count($entries); $i += $batch_size) {
$batch = array_slice($entries, $i, $batch_size);
foreach ($batch as $entry) {
try {
$result = $operation($entry);
$results[] = $result; // Store the result
} catch (\Exception $e) {
$error_message = "Error processing entry: " . json_encode($entry) . "\n" . $e->getMessage();
if ($error_handler) {
$error_handler($error_message, $entry); // Use custom error handler
} else {
$errors[] = ['entry' => $entry, 'error' => $error_message]; // Log error
}
}
}
}
if (!empty($errors)) {
return $errors; // Return errors if any
}
return $results;
}
// Example Usage (demonstration)
/*
// Sample operation (replace with your actual operation)
function process_entry(array $entry): string
{
// Simulate an error sometimes
if (rand(0, 10) < 2) {
throw new \Exception("Simulated error!");
}
return "Processed: " . $entry['id'];
}
// Example error handler
function my_error_handler($message, $entry) {
error_log("Custom Error: " . $message);
}
$entries = [
['id' => 1, 'data' => 'value1'],
['id' => 2, 'data' => 'value2'],
['id' => 3, 'data' => 'value3'],
['id' => 4, 'data' => 'value4'],
['id' => 5, 'data' => 'value5'],
];
$batch_size = 2;
$results = batch_operations($entries, $batch_size, 'process_entry', [$my_error_handler]);
if (empty($results)) {
echo "All entries processed successfully.\n";
} else {
echo "Errors occurred during processing:\n";
print_r($results);
}
*/
?>
Add your comment