1. <?php
  2. /**
  3. * Cleans data in collections for dry-run scenarios with error logging.
  4. *
  5. * @param array $collections An array of collections to clean.
  6. * @return array An array of cleaned collections.
  7. */
  8. function cleanCollections(array $collections): array
  9. {
  10. $cleanedCollections = [];
  11. $errors = [];
  12. foreach ($collections as $collection) {
  13. try {
  14. // Validate if the collection is an array
  15. if (!is_array($collection)) {
  16. $errors[] = "Invalid collection: Expected an array, got " . gettype($collection);
  17. continue; // Skip to the next collection
  18. }
  19. // Remove null/empty values
  20. $cleanedCollection = array_filter($collection, function ($value) {
  21. return $value !== null && $value !== '';
  22. });
  23. // Remove whitespace from strings
  24. $cleanedCollection = array_map(function ($value) {
  25. if (is_string($value)) {
  26. return trim($value);
  27. }
  28. return $value;
  29. }, $cleanedCollection);
  30. // Remove duplicates - using array_values to reindex
  31. $cleanedCollection = array_values(array_unique($cleanedCollection));
  32. $cleanedCollections[] = $cleanedCollection;
  33. } catch (Exception $e) {
  34. $errors[] = "Error cleaning collection: " . $e->getMessage() . ". Collection data: " . print_r($collection, true);
  35. }
  36. }
  37. // Log errors
  38. if (!empty($errors)) {
  39. error_log("Data Cleaning Errors:\n" . implode("\n", $errors));
  40. }
  41. return $cleanedCollections;
  42. }
  43. // Example Usage (for testing)
  44. /*
  45. $collections = [
  46. ['name' => ' John Doe ', 'age' => 30, 'city' => 'New York', 'email' => null, 'phone' => ''],
  47. ['product' => 'Widget', 'price' => 19.99, 'category' => '', 'quantity' => 10],
  48. ['item' => 'Book', 'title' => 'The Lord of the Rings', 'author' => 'J.R.R. Tolkien', 'isbn' => '978-0618260264'],
  49. 'invalid_collection',
  50. ];
  51. $cleaned = cleanCollections($collections);
  52. print_r($cleaned);
  53. */
  54. ?>

Add your comment