<?php
/**
* Validates query string configuration for monitoring.
*
* @param array $expected_params An associative array of expected query parameters.
* Keys are parameter names, values are expected data types (array('string', 'int', 'float', 'bool')).
* @return bool True if all expected parameters are present and have the correct type, false otherwise.
*/
function validateQueryString(array $expected_params): bool
{
$query_params = getQueryStringParameters(); // Helper function to get query string parameters.
foreach ($expected_params as $param_name => $expected_type) {
if (!isset($query_params[$param_name])) {
return false; // Required parameter missing.
}
$value = $query_params[$param_name];
if (!is_string($expected_type)) {
continue; // Skip if type is not a string
}
if ($expected_type === 'string' && !is_string($value)) {
return false; // Type mismatch: expected string, got something else.
} elseif ($expected_type === 'int' && (!is_int($value) || !is_numeric($value))) {
return false; // Type mismatch: expected int, but not an integer.
} elseif ($expected_type === 'float' && (!is_float($value) || !is_numeric($value))) {
return false; // Type mismatch: expected float, but not a float.
} elseif ($expected_type === 'bool' && ($value !== 'true' && $value !== 'false')) {
return false; // Type mismatch: expected bool, but not a boolean string.
}
}
return true; // All parameters are present and have the correct type.
}
/**
* Helper function to retrieve query string parameters.
*
* @return array An associative array of query string parameters.
*/
function getQueryStringParameters(): array
{
$params = [];
if (isset($_GET)) {
foreach ($_GET as $key => $value) {
$params[$key] = $value;
}
}
return $params;
}
// Example Usage:
/*
$expected_params = [
'status' => 'string',
'count' => 'int',
'debug' => 'bool'
];
if (validateQueryString($expected_params)) {
echo "Query string configuration is valid.\n";
} else {
echo "Query string configuration is invalid.\n";
}
*/
?>
Add your comment