1. <?php
  2. /**
  3. * Validates query string configuration for monitoring.
  4. *
  5. * @param array $expected_params An associative array of expected query parameters.
  6. * Keys are parameter names, values are expected data types (array('string', 'int', 'float', 'bool')).
  7. * @return bool True if all expected parameters are present and have the correct type, false otherwise.
  8. */
  9. function validateQueryString(array $expected_params): bool
  10. {
  11. $query_params = getQueryStringParameters(); // Helper function to get query string parameters.
  12. foreach ($expected_params as $param_name => $expected_type) {
  13. if (!isset($query_params[$param_name])) {
  14. return false; // Required parameter missing.
  15. }
  16. $value = $query_params[$param_name];
  17. if (!is_string($expected_type)) {
  18. continue; // Skip if type is not a string
  19. }
  20. if ($expected_type === 'string' && !is_string($value)) {
  21. return false; // Type mismatch: expected string, got something else.
  22. } elseif ($expected_type === 'int' && (!is_int($value) || !is_numeric($value))) {
  23. return false; // Type mismatch: expected int, but not an integer.
  24. } elseif ($expected_type === 'float' && (!is_float($value) || !is_numeric($value))) {
  25. return false; // Type mismatch: expected float, but not a float.
  26. } elseif ($expected_type === 'bool' && ($value !== 'true' && $value !== 'false')) {
  27. return false; // Type mismatch: expected bool, but not a boolean string.
  28. }
  29. }
  30. return true; // All parameters are present and have the correct type.
  31. }
  32. /**
  33. * Helper function to retrieve query string parameters.
  34. *
  35. * @return array An associative array of query string parameters.
  36. */
  37. function getQueryStringParameters(): array
  38. {
  39. $params = [];
  40. if (isset($_GET)) {
  41. foreach ($_GET as $key => $value) {
  42. $params[$key] = $value;
  43. }
  44. }
  45. return $params;
  46. }
  47. // Example Usage:
  48. /*
  49. $expected_params = [
  50. 'status' => 'string',
  51. 'count' => 'int',
  52. 'debug' => 'bool'
  53. ];
  54. if (validateQueryString($expected_params)) {
  55. echo "Query string configuration is valid.\n";
  56. } else {
  57. echo "Query string configuration is invalid.\n";
  58. }
  59. */
  60. ?>

Add your comment