1. <?php
  2. /**
  3. * Maps URL list fields for staging environments with basic input validation.
  4. *
  5. * @param array $urlList An array of URL list entries. Each entry is an associative array.
  6. * @param array $validationRules An array of validation rules. Each rule is an associative array.
  7. * Example: ['field_name' => ['type' => 'string', 'required' => true, 'min_length' => 5]]
  8. * @return array An array of validated URL list entries. Returns an empty array if input is invalid.
  9. */
  10. function mapAndValidateUrls(array $urlList, array $validationRules): array
  11. {
  12. $validatedUrls = [];
  13. foreach ($urlList as $urlEntry) {
  14. $validatedEntry = [];
  15. $isValid = true;
  16. foreach ($validationRules as $fieldName => $rule) {
  17. if (!isset($urlEntry[$fieldName])) {
  18. // Required field missing
  19. $isValid = false;
  20. break;
  21. }
  22. $value = trim($urlEntry[$fieldName]); //Remove whitespace
  23. //Type validation
  24. if (isset($rule['type'])) {
  25. switch ($rule['type']) {
  26. case 'string':
  27. if (!is_string($value)) {
  28. $isValid = false;
  29. break;
  30. }
  31. break;
  32. case 'integer':
  33. if (!is_int($value)) {
  34. $isValid = false;
  35. break;
  36. }
  37. break;
  38. case 'float':
  39. if (!is_float($value)) {
  40. $isValid = false;
  41. break;
  42. }
  43. break;
  44. default:
  45. // Ignore unknown types
  46. break;
  47. }
  48. }
  49. //Required validation
  50. if (isset($rule['required']) && $rule['required'] && empty($value)) {
  51. $isValid = false;
  52. break;
  53. }
  54. //Min length validation
  55. if (isset($rule['min_length']) && strlen($value) < $rule['min_length']) {
  56. $isValid = false;
  57. break;
  58. }
  59. //Other rules can be added here (e.g. email validation, regex)
  60. }
  61. if ($isValid) {
  62. $validatedEntry = $urlEntry; // Copy the original entry
  63. $validatedUrls[] = $validatedEntry;
  64. }
  65. }
  66. return $validatedUrls;
  67. }
  68. //Example Usage:
  69. /*
  70. $urlList = [
  71. ['url_id' => 1, 'url' => 'https://example.com', 'description' => 'Test URL'],
  72. ['url_id' => 2, 'url' => ' ', 'description' => 'Test URL'], //Empty string
  73. ['url_id' => 3, 'url' => '123', 'description' => 'Test URL'], // Integer
  74. ['url_id' => 4, 'url' => 'abc123def', 'description' => 'Test URL'], //String
  75. ];
  76. $validationRules = [
  77. 'url_id' => ['type' => 'integer', 'required' => true],
  78. 'url' => ['type' => 'string', 'required' => true, 'min_length' => 5],
  79. 'description' => ['type' => 'string']
  80. ];
  81. $validatedUrls = mapAndValidateUrls($urlList, $validationRules);
  82. print_r($validatedUrls);
  83. */
  84. ?>

Add your comment