1. <?php
  2. /**
  3. * Decodes and validates a record with manual override capability.
  4. *
  5. * @param array $record The input record data.
  6. * @param array $validationRules An associative array of validation rules.
  7. * Key: Field name, Value: Array of validation rules (e.g., ['required', 'string', 'min=5']).
  8. * @param array $manualOverrides An associative array of field names and their overridden values.
  9. * @return array|bool Returns the validated record if successful, false otherwise.
  10. */
  11. function decodeAndValidateRecord(array $record, array $validationRules, array $manualOverrides): array|bool
  12. {
  13. $validatedRecord = $record;
  14. foreach ($validationRules as $fieldName => $rules) {
  15. if (array_key_exists($fieldName, $manualOverrides)) {
  16. $validatedRecord[$fieldName] = $manualOverrides[$fieldName];
  17. continue; // Skip validation if manually overridden
  18. }
  19. $value = $validatedRecord[$fieldName] ?? null; // Handle potentially missing fields
  20. foreach ($rules as $rule) {
  21. switch ($rule) {
  22. case 'required':
  23. if (empty($value)) {
  24. return false; // Required field is missing
  25. }
  26. break;
  27. case 'string':
  28. if (!is_string($value)) {
  29. return false; // Field must be a string
  30. }
  31. break;
  32. case 'min':
  33. if (strlen($value) < (int)$value['min']) {
  34. return false; // String must be at least min characters long
  35. }
  36. break;
  37. case 'max':
  38. if (strlen($value) > (int)$value['max']) {
  39. return false; // String must be at most max characters long
  40. }
  41. break;
  42. case 'email':
  43. if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
  44. return false; // Field must be a valid email
  45. }
  46. break;
  47. case 'numeric':
  48. if (!is_numeric($value)) {
  49. return false;
  50. }
  51. break;
  52. default:
  53. // Unknown validation rule - log or handle as needed
  54. error_log("Unknown validation rule: " . $rule . " for field: " . $fieldName);
  55. return false;
  56. }
  57. }
  58. }
  59. return $validatedRecord; // Record is valid
  60. }
  61. ?>

Add your comment