<?php
/**
* Cleans data in collections for dry-run scenarios with error logging.
*
* @param array $collections An array of collections to clean.
* @return array An array of cleaned collections.
*/
function cleanCollections(array $collections): array
{
$cleanedCollections = [];
$errors = [];
foreach ($collections as $collection) {
try {
// Validate if the collection is an array
if (!is_array($collection)) {
$errors[] = "Invalid collection: Expected an array, got " . gettype($collection);
continue; // Skip to the next collection
}
// Remove null/empty values
$cleanedCollection = array_filter($collection, function ($value) {
return $value !== null && $value !== '';
});
// Remove whitespace from strings
$cleanedCollection = array_map(function ($value) {
if (is_string($value)) {
return trim($value);
}
return $value;
}, $cleanedCollection);
// Remove duplicates - using array_values to reindex
$cleanedCollection = array_values(array_unique($cleanedCollection));
$cleanedCollections[] = $cleanedCollection;
} catch (Exception $e) {
$errors[] = "Error cleaning collection: " . $e->getMessage() . ". Collection data: " . print_r($collection, true);
}
}
// Log errors
if (!empty($errors)) {
error_log("Data Cleaning Errors:\n" . implode("\n", $errors));
}
return $cleanedCollections;
}
// Example Usage (for testing)
/*
$collections = [
['name' => ' John Doe ', 'age' => 30, 'city' => 'New York', 'email' => null, 'phone' => ''],
['product' => 'Widget', 'price' => 19.99, 'category' => '', 'quantity' => 10],
['item' => 'Book', 'title' => 'The Lord of the Rings', 'author' => 'J.R.R. Tolkien', 'isbn' => '978-0618260264'],
'invalid_collection',
];
$cleaned = cleanCollections($collections);
print_r($cleaned);
*/
?>
Add your comment