<?php
/**
* Exports string results for testing with fallback logic.
*
* @param array $results An array of string results.
* @param string $filename The name of the file to export to.
* @param array $fallback_methods An array of fallback methods to try.
* @return bool True on success, false on failure.
*/
function exportStringResults(array $results, string $filename, array $fallback_methods = []): bool
{
try {
// Attempt to write the results to the specified file.
$success = file_put_contents($filename, json_encode($results));
if ($success !== false) {
return true; // Success
} else {
// File write failed, attempt fallback methods.
foreach ($fallback_methods as $method) {
$success = $method($filename, $results);
if ($success !== false) {
return true; // Success with fallback
}
}
return false; // Failed with all fallback methods.
}
} catch (Exception $e) {
// Handle any exceptions during file operations.
if(empty($fallback_methods)){
return false; //No fallback methods available
}
foreach ($fallback_methods as $method) {
$success = $method($filename, $results);
if ($success !== false) {
return true; // Success with fallback
}
}
return false; // Failed with all fallback methods.
}
}
/**
* Example fallback method: Writes results to a CSV file.
*
* @param string $filename The name of the file to write to.
* @param array $results The results to write.
* @return bool True on success, false on failure.
*/
function exportStringResultsCsv(string $filename, array $results): bool
{
$csv_string = fopen($filename, 'w');
if ($csv_string === false) {
return false;
}
foreach ($results as $result) {
fputcsv($csv_string, [$result]);
}
fclose($csv_string);
return true;
}
/**
* Example fallback method: Outputs to the console.
*
* @param string $filename The name of the file to write to.
* @param array $results The results to write.
* @return bool True on success, false on failure.
*/
function exportStringResultsConsole(string $filename, array $results): bool
{
echo json_encode($results) . PHP_EOL;
return true;
}
// Example Usage:
$results = ['result1', 'result2', 'result3'];
$filename = 'results.json';
$fallback_methods = [exportStringResultsCsv, exportStringResultsConsole];
if (exportStringResults($results, $filename, $fallback_methods)) {
echo "Results exported successfully!\n";
} else {
echo "Failed to export results.\n";
}
?>
Add your comment