<?php
/**
* Validates HTTP response configuration for short-lived tasks.
*
* @param array $config An array containing the response configuration.
* Example:
* [
* 'status_code' => 200,
* 'headers' => [
* 'Content-Type' => 'application/json',
* 'Cache-Control' => 'no-cache, no-store, must-revalidate',
* 'Pragma' => 'no-cache',
* 'Expires' => '0',
* ],
* 'body_length_limit' => 1024, // in bytes
* ]
*
* @return bool True if the configuration is valid, false otherwise.
*/
function validateResponseConfig(array $config): bool
{
// Check if status code is a valid HTTP status code (100-599)
if (!is_int($config['status_code']) || $config['status_code'] < 100 || $config['status_code'] > 599) {
error_log("Invalid status code: " . var_export($config['status_code'], true));
return false;
}
// Check if headers is an array
if (!is_array($config['headers'])) {
error_log("Headers must be an array: " . var_export($config['headers'], true));
return false;
}
// Validate specific header keys (example: Content-Type, Cache-Control)
if (isset($config['headers']['Content-Type']) && !is_string($config['headers']['Content-Type'])) {
error_log("Invalid Content-Type header: " . var_export($config['headers']['Content-Type'], true));
return false;
}
if (isset($config['headers']['Cache-Control']) && !is_string($config['headers']['Cache-Control'])) {
error_log("Invalid Cache-Control header: " . var_export($config['headers']['Cache-Control'], true));
return false;
}
if (isset($config['headers']['Pragma']) && !is_string($config['headers']['Pragma'])) {
error_log("Invalid Pragma header: " . var_export($config['headers']['Pragma'], true));
return false;
}
if (isset($config['headers']['Expires']) && !is_string($config['headers']['Expires'])) {
error_log("Invalid Expires header: " . var_export($config['headers']['Expires'], true));
return false;
}
// Check body length limit
if (!is_int($config['body_length_limit']) || $config['body_length_limit'] <= 0) {
error_log("Invalid body_length_limit: " . var_export($config['body_length_limit'], true));
return false;
}
return true;
}
/**
* Example usage
*/
$validConfig = [
'status_code' => 200,
'headers' => [
'Content-Type' => 'application/json',
'Cache-Control' => 'no-cache, no-store, must-revalidate',
'Pragma' => 'no-cache',
'Expires' => '0',
],
'body_length_limit' => 1024,
];
$invalidConfig = [
'status_code' => 600, // Invalid status code
'headers' => 'not an array', // Invalid headers
'body_length_limit' => -1, // Invalid body length
];
if (validateResponseConfig($validConfig)) {
echo "Valid configuration.\n";
} else {
echo "Invalid configuration.\n";
}
if (validateResponseConfig($invalidConfig)) {
echo "Valid configuration.\n";
} else {
echo "Invalid configuration.\n";
}
?>
Add your comment