1. <?php
  2. /**
  3. * Normalizes cookie data based on a configuration file.
  4. *
  5. * @param array $cookies An array of cookies to normalize.
  6. * @param string $config_file Path to the configuration file.
  7. *
  8. * @return array Normalized cookie data.
  9. * @throws Exception If configuration file not found or invalid.
  10. */
  11. function normalizeCookies(array $cookies, string $config_file): array
  12. {
  13. // Load configuration
  14. $config = loadConfig($config_file);
  15. if (!$config) {
  16. throw new Exception("Configuration file not found or invalid: " . $config_file);
  17. }
  18. $normalized_cookies = [];
  19. foreach ($cookies as $cookie) {
  20. $normalized_cookie = [];
  21. foreach ($config['cookie_fields'] as $field) {
  22. if (isset($cookie[$field])) {
  23. $normalized_cookie[$field] = normalizeField($cookie[$field], $config[$field]);
  24. }
  25. }
  26. $normalized_cookies[] = $normalized_cookie;
  27. }
  28. return $normalized_cookies;
  29. }
  30. /**
  31. * Normalizes a single cookie field based on its configuration.
  32. *
  33. * @param mixed $value The raw cookie value.
  34. * @param array $config The configuration for the field.
  35. *
  36. * @return mixed The normalized cookie value.
  37. */
  38. function normalizeField($value, array $config)
  39. {
  40. switch ($config['type']) {
  41. case 'int':
  42. $value = (int)$value;
  43. break;
  44. case 'float':
  45. $value = (float)$value;
  46. break;
  47. case 'string':
  48. $value = (string)$value;
  49. break;
  50. case 'boolean':
  51. $value = (bool)$value;
  52. break;
  53. case 'date':
  54. $value = formatDate($value, $config['format']);
  55. break;
  56. default:
  57. $value = $value; // No normalization needed
  58. }
  59. return $value;
  60. }
  61. /**
  62. * Formats a date according to the specified format.
  63. *
  64. * @param mixed $date The date value.
  65. * @param string $format The date format.
  66. *
  67. * @return string The formatted date.
  68. */
  69. function formatDate($date, string $format): string
  70. {
  71. if (is_numeric($date)) {
  72. return date("Y-m-d H:i:s", $date);
  73. }
  74. return $date;
  75. }
  76. /**
  77. * Loads configuration from a file.
  78. *
  79. * @param string $file_path The path to the configuration file.
  80. *
  81. * @return array|null The configuration array, or null if loading fails.
  82. */
  83. function loadConfig(string $file_path): ?array
  84. {
  85. if (file_exists($file_path)) {
  86. $config = json_decode(file_get_contents($file_path), true);
  87. if (json_last_error() === JSON_ERROR_NONE) {
  88. return $config;
  89. }
  90. }
  91. return null;
  92. }
  93. ?>

Add your comment