<?php
/**
* Function to deserialize log stream data for staging environments.
*
* This function takes a string containing serialized data (e.g., from a log stream)
* and attempts to decode it into a PHP array or object. Handles potential errors
* gracefully, logging issues and returning an empty array on failure.
*
* @param string $serializedData The serialized data string.
* @return array|null Decoded data as an array, or null on failure.
*/
function deserializeLogStreamData(string $serializedData): ?array
{
// Remove any leading/trailing whitespace
$serializedData = trim($serializedData);
// Check if the data is empty or null
if (empty($serializedData)) {
// Return an empty array if the input is empty
return [];
}
// Attempt to unserialize the data. Using `error_reporting` and `error_log`
// for better error handling in staging environments.
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 0); //Disable error display in production/staging
error_log("Deserialization attempt: " . $serializedData); //Log the input data for debugging
$data = unserialize($serializedData);
// Check if unserialize was successful
if ($data === false) {
error_log("Deserialization failed: " . error_get_last()['message'] . " - Data: " . $serializedData);
return []; // Return an empty array on failure
}
//Return the deserialized data
return $data;
}
/**
* Example Usage (for testing/demonstration)
*/
/*
$logData = '{"timestamp": "2024-10-27T10:00:00Z", "message": "Application started"}';
$decodedData = deserializeLogStreamData($logData);
if (!empty($decodedData)) {
print_r($decodedData);
} else {
echo "Failed to deserialize log data.\n";
}
$invalidData = 'This is not valid JSON';
$decodedData = deserializeLogStreamData($invalidData);
if (!empty($decodedData)) {
print_r($decodedData);
} else {
echo "Failed to deserialize log data.\n";
}
*/
?>
Add your comment