1. <?php
  2. /**
  3. * Function to deserialize log stream data for staging environments.
  4. *
  5. * This function takes a string containing serialized data (e.g., from a log stream)
  6. * and attempts to decode it into a PHP array or object. Handles potential errors
  7. * gracefully, logging issues and returning an empty array on failure.
  8. *
  9. * @param string $serializedData The serialized data string.
  10. * @return array|null Decoded data as an array, or null on failure.
  11. */
  12. function deserializeLogStreamData(string $serializedData): ?array
  13. {
  14. // Remove any leading/trailing whitespace
  15. $serializedData = trim($serializedData);
  16. // Check if the data is empty or null
  17. if (empty($serializedData)) {
  18. // Return an empty array if the input is empty
  19. return [];
  20. }
  21. // Attempt to unserialize the data. Using `error_reporting` and `error_log`
  22. // for better error handling in staging environments.
  23. error_reporting(E_ALL | E_STRICT);
  24. ini_set('display_errors', 0); //Disable error display in production/staging
  25. error_log("Deserialization attempt: " . $serializedData); //Log the input data for debugging
  26. $data = unserialize($serializedData);
  27. // Check if unserialize was successful
  28. if ($data === false) {
  29. error_log("Deserialization failed: " . error_get_last()['message'] . " - Data: " . $serializedData);
  30. return []; // Return an empty array on failure
  31. }
  32. //Return the deserialized data
  33. return $data;
  34. }
  35. /**
  36. * Example Usage (for testing/demonstration)
  37. */
  38. /*
  39. $logData = '{"timestamp": "2024-10-27T10:00:00Z", "message": "Application started"}';
  40. $decodedData = deserializeLogStreamData($logData);
  41. if (!empty($decodedData)) {
  42. print_r($decodedData);
  43. } else {
  44. echo "Failed to deserialize log data.\n";
  45. }
  46. $invalidData = 'This is not valid JSON';
  47. $decodedData = deserializeLogStreamData($invalidData);
  48. if (!empty($decodedData)) {
  49. print_r($decodedData);
  50. } else {
  51. echo "Failed to deserialize log data.\n";
  52. }
  53. */
  54. ?>

Add your comment