<?php
/**
* Wraps file path logic with retry and error handling.
*
* @param string $filePath The file path to operate on.
* @param callable $operation A callable (function) that takes a file path and performs an operation.
* @param int $maxRetries The maximum number of retry attempts.
* @param int $retryDelay The delay in seconds between retries.
* @return mixed The result of the operation, or null on failure after all retries.
* @throws Exception If the operation fails after all retries.
*/
function safeFileOperation(string $filePath, callable $operation, int $maxRetries = 3, int $retryDelay = 1): mixed
{
$retries = 0;
while ($retries < $maxRetries) {
try {
return $operation($filePath); // Attempt the operation
} catch (Exception $e) {
$retries++;
if ($retries >= $maxRetries) {
throw $e; // Re-throw the exception if max retries reached
}
// Wait before retrying
sleep($retryDelay);
}
}
throw new Exception("File operation failed after multiple retries."); // Should not reach here, but good to have
}
// Example usage (replace with your actual file path and operation)
/*
$filePath = '/path/to/your/file.txt';
$result = safeFileOperation($filePath, function (string $path) {
// Your file operation logic here
// e.g., read file, write file, etc.
try {
$fileContents = file_get_contents($path);
return $fileContents;
} catch (Exception $e) {
throw new Exception("Error reading file: " . $e->getMessage());
}
});
if ($result !== null) {
echo "Operation successful: " . $result . PHP_EOL;
} else {
echo "Operation failed after multiple retries." . PHP_EOL;
}
*/
?>
Add your comment