1. <?php
  2. /**
  3. * Wraps file path logic with retry and error handling.
  4. *
  5. * @param string $filePath The file path to operate on.
  6. * @param callable $operation A callable (function) that takes a file path and performs an operation.
  7. * @param int $maxRetries The maximum number of retry attempts.
  8. * @param int $retryDelay The delay in seconds between retries.
  9. * @return mixed The result of the operation, or null on failure after all retries.
  10. * @throws Exception If the operation fails after all retries.
  11. */
  12. function safeFileOperation(string $filePath, callable $operation, int $maxRetries = 3, int $retryDelay = 1): mixed
  13. {
  14. $retries = 0;
  15. while ($retries < $maxRetries) {
  16. try {
  17. return $operation($filePath); // Attempt the operation
  18. } catch (Exception $e) {
  19. $retries++;
  20. if ($retries >= $maxRetries) {
  21. throw $e; // Re-throw the exception if max retries reached
  22. }
  23. // Wait before retrying
  24. sleep($retryDelay);
  25. }
  26. }
  27. throw new Exception("File operation failed after multiple retries."); // Should not reach here, but good to have
  28. }
  29. // Example usage (replace with your actual file path and operation)
  30. /*
  31. $filePath = '/path/to/your/file.txt';
  32. $result = safeFileOperation($filePath, function (string $path) {
  33. // Your file operation logic here
  34. // e.g., read file, write file, etc.
  35. try {
  36. $fileContents = file_get_contents($path);
  37. return $fileContents;
  38. } catch (Exception $e) {
  39. throw new Exception("Error reading file: " . $e->getMessage());
  40. }
  41. });
  42. if ($result !== null) {
  43. echo "Operation successful: " . $result . PHP_EOL;
  44. } else {
  45. echo "Operation failed after multiple retries." . PHP_EOL;
  46. }
  47. */
  48. ?>

Add your comment