<?php
/**
* Extends API payload validation with memory efficiency.
*
* This function iterates through the payload data, performing validation
* checks on individual elements without loading the entire payload into memory.
* Suitable for large JSON responses.
*
* @param string $json_string The JSON string to validate.
* @param array $validation_rules An array of validation rules. Each rule should be an associative array with keys: 'field', 'type', 'validate_function', 'message'.
* @return array|false An array of validation errors if any, or false on failure to decode JSON.
*/
function validateApiPayload(string $json_string, array $validation_rules): array|false
{
$errors = [];
$data = json_decode($json_string, true);
if ($data === null) {
return false; // JSON decode failed
}
foreach ($validation_rules as $rule) {
$field = $rule['field'];
$type = $rule['type'];
$validate_function = $rule['validate_function'];
$message = $rule['message'];
// Check if the field exists in the data
if (!isset($data[$field])) {
$errors[] = ['field' => $field, 'message' => $message];
continue;
}
// Validate the field based on the specified type
$validation_result = call_user_func($validate_function, $data[$field]);
if ($validation_result === false) {
$errors[] = ['field' => $field, 'message' => $validation_result];
}
}
return $errors;
}
/**
* Example validation functions. Can be extended as needed.
*
* @param mixed $value The value to validate.
* @return bool|string Returns true on success, or an error message on failure.
*/
function validateString(string $value)
{
return !empty($value);
}
function validateInt(int $value)
{
return is_int($value);
}
function validateEmail(string $value)
{
return filter_var($value, FILTER_VALIDATE_EMAIL) !== false;
}
function validateArray(array $value) {
return is_array($value);
}
// Example Usage:
/*
$json = '[
{"name": "John Doe", "email": "john.doe@example.com", "age": 30},
{"name": "Jane Smith", "email": "invalid-email", "age": "abc"}
]';
$rules = [
['field' => 'name', 'type' => 'validateString', 'validate_function' => 'validateString', 'message' => 'Name cannot be empty.'],
['field' => 'email', 'type' => 'validateEmail', 'validate_function' => 'validateEmail', 'message' => 'Invalid email address.'],
['field' => 'age', 'type' => 'validateInt', 'validate_function' => 'validateInt', 'message' => 'Age must be an integer.'],
['field' => 'age', 'type' => 'validateInt', 'validate_function' => 'validateInt', 'message' => 'Age must be an integer.'],
['field' => 'address', 'type' => 'validateArray', 'validate_function' => 'validateArray', 'message' => 'Address must be an array.'],
];
$errors = validateApiPayload($json, $rules);
if (empty($errors)) {
echo "Payload is valid.\n";
} else {
echo "Validation errors:\n";
foreach ($errors as $error) {
echo " Field: " . $error['field'] . ", Message: " . $error['message'] . "\n";
}
}
*/
?>
Add your comment