1. <?php
  2. /**
  3. * Exports string results for testing with fallback logic.
  4. *
  5. * @param array $results An array of string results.
  6. * @param string $filename The name of the file to export to.
  7. * @param array $fallback_methods An array of fallback methods to try.
  8. * @return bool True on success, false on failure.
  9. */
  10. function exportStringResults(array $results, string $filename, array $fallback_methods = []): bool
  11. {
  12. try {
  13. // Attempt to write the results to the specified file.
  14. $success = file_put_contents($filename, json_encode($results));
  15. if ($success !== false) {
  16. return true; // Success
  17. } else {
  18. // File write failed, attempt fallback methods.
  19. foreach ($fallback_methods as $method) {
  20. $success = $method($filename, $results);
  21. if ($success !== false) {
  22. return true; // Success with fallback
  23. }
  24. }
  25. return false; // Failed with all fallback methods.
  26. }
  27. } catch (Exception $e) {
  28. // Handle any exceptions during file operations.
  29. if(empty($fallback_methods)){
  30. return false; //No fallback methods available
  31. }
  32. foreach ($fallback_methods as $method) {
  33. $success = $method($filename, $results);
  34. if ($success !== false) {
  35. return true; // Success with fallback
  36. }
  37. }
  38. return false; // Failed with all fallback methods.
  39. }
  40. }
  41. /**
  42. * Example fallback method: Writes results to a CSV file.
  43. *
  44. * @param string $filename The name of the file to write to.
  45. * @param array $results The results to write.
  46. * @return bool True on success, false on failure.
  47. */
  48. function exportStringResultsCsv(string $filename, array $results): bool
  49. {
  50. $csv_string = fopen($filename, 'w');
  51. if ($csv_string === false) {
  52. return false;
  53. }
  54. foreach ($results as $result) {
  55. fputcsv($csv_string, [$result]);
  56. }
  57. fclose($csv_string);
  58. return true;
  59. }
  60. /**
  61. * Example fallback method: Outputs to the console.
  62. *
  63. * @param string $filename The name of the file to write to.
  64. * @param array $results The results to write.
  65. * @return bool True on success, false on failure.
  66. */
  67. function exportStringResultsConsole(string $filename, array $results): bool
  68. {
  69. echo json_encode($results) . PHP_EOL;
  70. return true;
  71. }
  72. // Example Usage:
  73. $results = ['result1', 'result2', 'result3'];
  74. $filename = 'results.json';
  75. $fallback_methods = [exportStringResultsCsv, exportStringResultsConsole];
  76. if (exportStringResults($results, $filename, $fallback_methods)) {
  77. echo "Results exported successfully!\n";
  78. } else {
  79. echo "Failed to export results.\n";
  80. }
  81. ?>

Add your comment