<?php
/**
* Decodes and validates a record with manual override capability.
*
* @param array $record The input record data.
* @param array $validationRules An associative array of validation rules.
* Key: Field name, Value: Array of validation rules (e.g., ['required', 'string', 'min=5']).
* @param array $manualOverrides An associative array of field names and their overridden values.
* @return array|bool Returns the validated record if successful, false otherwise.
*/
function decodeAndValidateRecord(array $record, array $validationRules, array $manualOverrides): array|bool
{
$validatedRecord = $record;
foreach ($validationRules as $fieldName => $rules) {
if (array_key_exists($fieldName, $manualOverrides)) {
$validatedRecord[$fieldName] = $manualOverrides[$fieldName];
continue; // Skip validation if manually overridden
}
$value = $validatedRecord[$fieldName] ?? null; // Handle potentially missing fields
foreach ($rules as $rule) {
switch ($rule) {
case 'required':
if (empty($value)) {
return false; // Required field is missing
}
break;
case 'string':
if (!is_string($value)) {
return false; // Field must be a string
}
break;
case 'min':
if (strlen($value) < (int)$value['min']) {
return false; // String must be at least min characters long
}
break;
case 'max':
if (strlen($value) > (int)$value['max']) {
return false; // String must be at most max characters long
}
break;
case 'email':
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
return false; // Field must be a valid email
}
break;
case 'numeric':
if (!is_numeric($value)) {
return false;
}
break;
default:
// Unknown validation rule - log or handle as needed
error_log("Unknown validation rule: " . $rule . " for field: " . $fieldName);
return false;
}
}
}
return $validatedRecord; // Record is valid
}
?>
Add your comment