1. <?php
  2. /**
  3. * Function to format and limit time output for isolated environments with verbose logging.
  4. *
  5. * @param string $timestamp The timestamp to format.
  6. * @param string $format The desired format (e.g., 'Y-m-d H:i:s').
  7. * @param string $logMessage A message for logging.
  8. * @return string The formatted timestamp, or an empty string if logging is disabled.
  9. */
  10. function formatAndLimitTime(string $timestamp, string $format, string $logMessage = ''): string
  11. {
  12. // Check if logging is enabled (can be a global config)
  13. if (isset($_ENV['LOG_ENABLED']) && $_ENV['LOG_ENABLED'] === 'false') {
  14. return ''; // Disable output if logging is off.
  15. }
  16. try {
  17. $dateTime = new DateTime($timestamp); // Create a DateTime object
  18. $formattedTime = $dateTime->format($format); // Format the time
  19. } catch (Exception $e) {
  20. //Handle invalid timestamps gracefully.
  21. error_log("Invalid timestamp: " . $timestamp . ". Error: " . $e->getMessage());
  22. return '';
  23. }
  24. // Limit output to specific environments (e.g., isolated environments)
  25. if (isset($_ENV['ENVIRONMENT']) && $_ENV['ENVIRONMENT'] === 'isolated') {
  26. error_log($logMessage . " - Timestamp: " . $formattedTime); // Log the timestamp
  27. return $formattedTime; // Output the formatted time
  28. } else {
  29. return ''; // Don't output if not in the isolated environment.
  30. }
  31. }
  32. // Example Usage
  33. $timestamp = '2024-01-27 10:30:00';
  34. $format = 'H:i:s';
  35. $logMessage = 'Processing data...';
  36. $output = formatAndLimitTime($timestamp, $format, $logMessage);
  37. if ($output !== '') {
  38. echo $output . PHP_EOL; // Output only if it's in the isolated environment and logging is enabled.
  39. }
  40. $timestamp = 'invalid-timestamp';
  41. $output = formatAndLimitTime($timestamp, $format, $logMessage);
  42. if ($output === '') {
  43. echo "Invalid timestamp handled correctly." . PHP_EOL;
  44. }
  45. ?>

Add your comment