<?php
/**
* Function to format and limit time output for isolated environments with verbose logging.
*
* @param string $timestamp The timestamp to format.
* @param string $format The desired format (e.g., 'Y-m-d H:i:s').
* @param string $logMessage A message for logging.
* @return string The formatted timestamp, or an empty string if logging is disabled.
*/
function formatAndLimitTime(string $timestamp, string $format, string $logMessage = ''): string
{
// Check if logging is enabled (can be a global config)
if (isset($_ENV['LOG_ENABLED']) && $_ENV['LOG_ENABLED'] === 'false') {
return ''; // Disable output if logging is off.
}
try {
$dateTime = new DateTime($timestamp); // Create a DateTime object
$formattedTime = $dateTime->format($format); // Format the time
} catch (Exception $e) {
//Handle invalid timestamps gracefully.
error_log("Invalid timestamp: " . $timestamp . ". Error: " . $e->getMessage());
return '';
}
// Limit output to specific environments (e.g., isolated environments)
if (isset($_ENV['ENVIRONMENT']) && $_ENV['ENVIRONMENT'] === 'isolated') {
error_log($logMessage . " - Timestamp: " . $formattedTime); // Log the timestamp
return $formattedTime; // Output the formatted time
} else {
return ''; // Don't output if not in the isolated environment.
}
}
// Example Usage
$timestamp = '2024-01-27 10:30:00';
$format = 'H:i:s';
$logMessage = 'Processing data...';
$output = formatAndLimitTime($timestamp, $format, $logMessage);
if ($output !== '') {
echo $output . PHP_EOL; // Output only if it's in the isolated environment and logging is enabled.
}
$timestamp = 'invalid-timestamp';
$output = formatAndLimitTime($timestamp, $format, $logMessage);
if ($output === '') {
echo "Invalid timestamp handled correctly." . PHP_EOL;
}
?>
Add your comment