1. <?php
  2. /**
  3. * Transforms form data for maintenance tasks with retry logic.
  4. *
  5. * @param array $formData Array of form data.
  6. * @param int $maxRetries Maximum number of retry attempts.
  7. * @return array|null Transformed data or null on failure after all retries.
  8. */
  9. function transformMaintenanceFormData(array $formData, int $maxRetries = 3): ?array
  10. {
  11. $retries = 0;
  12. $transformedData = null;
  13. while ($retries < $maxRetries) {
  14. try {
  15. // Data validation and transformation logic here
  16. $transformedData = validateAndTransformData($formData);
  17. if ($transformedData !== null) {
  18. return $transformedData;
  19. }
  20. } catch (Exception $e) {
  21. $retries++;
  22. error_log("Maintenance Task: Transformation failed (attempt " . $retries . "): " . $e->getMessage());
  23. if ($retries < $maxRetries) {
  24. // Wait before retrying (optional)
  25. sleep(1); // Wait 1 second
  26. }
  27. }
  28. }
  29. error_log("Maintenance Task: Transformation failed after " . $maxRetries . " attempts.");
  30. return null; // Return null if transformation fails after all retries
  31. }
  32. /**
  33. * Validates and transforms the form data. This is where the core logic goes.
  34. * Replace with your specific validation and transformation rules.
  35. *
  36. * @param array $formData Form data.
  37. * @return array|null Transformed data, or null if validation fails.
  38. */
  39. function validateAndTransformData(array $formData): ?array
  40. {
  41. // Example validation and transformation - adapt to your needs
  42. if (empty($formData['task_type'])) {
  43. throw new Exception("Task type is required.");
  44. }
  45. if (!in_array($formData['priority'], ['high', 'medium', 'low'])) {
  46. throw new Exception("Invalid priority value.");
  47. }
  48. $transformedData = [
  49. 'task_type' => strtolower($formData['task_type']), // Convert to lowercase
  50. 'priority' => $formData['priority'],
  51. 'description' => trim($formData['description']), // Remove whitespace
  52. 'scheduled_date' => date('Y-m-d', strtotime($formData['scheduled_date'])), // Format date
  53. ];
  54. return $transformedData;
  55. }
  56. // Example Usage:
  57. $form_data = [
  58. 'task_type' => 'High',
  59. 'priority' => 'high',
  60. 'description' => 'Fix the server',
  61. 'scheduled_date' => '2024-12-25'
  62. ];
  63. $transformed_data = transformMaintenanceFormData($form_data);
  64. if ($transformed_data) {
  65. echo "<pre>";
  66. print_r($transformed_data);
  67. echo "</pre>";
  68. } else {
  69. echo "Transformation failed.";
  70. }
  71. ?>

Add your comment