1. <?php
  2. /**
  3. * Decodes and validates a record input for hypothesis validation.
  4. *
  5. * @param string $record_string The input record as a string.
  6. * @param array $expected_fields An array of expected field names.
  7. * @return array|null An associative array representing the decoded record if valid, null otherwise.
  8. */
  9. function decode_and_validate_record(string $record_string, array $expected_fields): ?array
  10. {
  11. // Decode the record string (assuming CSV format for simplicity).
  12. $record_data = str_getcsv($record_string);
  13. // Check if the record data is empty.
  14. if (empty($record_data)) {
  15. error_log("Invalid record: Empty record.");
  16. return null;
  17. }
  18. // Sanity checks: Check number of fields against expected fields.
  19. if (count($record_data) !== count($expected_fields)) {
  20. error_log("Invalid record: Incorrect number of fields.");
  21. return null;
  22. }
  23. // Create an associative array to store the decoded record.
  24. $decoded_record = [];
  25. // Loop through the expected fields and assign values from the record data.
  26. for ($i = 0; $i < count($expected_fields); $i++) {
  27. $field_name = trim($expected_fields[$i]); //Trim whitespace
  28. if (empty($field_name)) {
  29. error_log("Invalid record: Empty field name.");
  30. return null;
  31. }
  32. $decoded_record[$field_name] = trim($record_data[$i]); //Trim whitespace
  33. }
  34. // Add more specific validation logic here if needed.
  35. // For example, data type validation, range checks, etc.
  36. return $decoded_record;
  37. }
  38. //Example usage:
  39. /*
  40. $record_string = "id,name,age,city";
  41. $expected_fields = ["id", "name", "age", "city"];
  42. $record = decode_and_validate_record($record_string, $expected_fields);
  43. if ($record) {
  44. print_r($record);
  45. } else {
  46. echo "Record validation failed.";
  47. }
  48. */
  49. ?>

Add your comment