<?php
/**
* Verifies the integrity of metadata for batch processing.
* Handles potential edge cases like missing fields, incorrect data types, and invalid values.
*
* @param array $metadata An array of metadata for each item in the batch.
* @param array $requiredFields An array of required metadata fields.
* @return array An array of errors found during validation. Empty array if validation passes.
*/
function validateMetadata(array $metadata, array $requiredFields): array
{
$errors = [];
foreach ($metadata as $index => $item) {
$itemErrors = [];
foreach ($requiredFields as $field) {
if (!isset($item[$field])) {
$itemErrors[] = "Missing required field: " . $field;
} elseif (empty($item[$field])) {
$itemErrors[] = "Field '" . $field . "' cannot be empty.";
} else {
// Type validation and value checks
$expectedType = null;
$allowedValues = [];
switch ($field) {
case 'id':
$expectedType = 'int';
break;
case 'status':
$expectedType = 'string';
$allowedValues = ['pending', 'processing', 'completed', 'failed'];
break;
case 'timestamp':
$expectedType = 'int'; // Unix timestamp
break;
case 'data_type':
$expectedType = 'string';
$allowedValues = ['image', 'video', 'audio', 'text'];
break;
default:
// Add more field type and value checks as needed
break;
}
if ($expectedType !== null) {
if (!is_int($item[$field]) && $expectedType === 'int') {
$itemErrors[] = "Field '" . $field . "' must be an integer.";
} elseif (!is_string($item[$field]) && $expectedType === 'string') {
$itemErrors[] = "Field '" . $field . "' must be a string.";
} elseif (!is_numeric($item[$field]) && $expectedType === 'float') {
$itemErrors[] = "Field '" . $field . "' must be a number.";
}
}
if (is_array($allowedValues) && !in_array($item[$field], $allowedValues)) {
$itemErrors[] = "Field '" . $field . "' has an invalid value. Allowed values: " . implode(', ', $allowedValues);
}
}
}
if (!empty($itemErrors)) {
$errors[] = [
'index' => $index,
'errors' => $itemErrors,
];
}
}
return $errors;
}
// Example Usage (replace with your actual data)
//$metadata = [
// ['id' => 1, 'status' => 'processing', 'timestamp' => 1678886400, 'data_type' => 'image'],
// ['id' => 2, 'status' => 'completed', 'timestamp' => 1678886460, 'data_type' => 'video'],
// ['status' => '', 'timestamp' => 1678886520, 'data_type' => 'audio'], //Missing id and empty status
// ['id' => 'abc', 'status' => 'pending', 'timestamp' => 1678886580, 'data_type' => 'text'], //Invalid id type
// ['id' => 3, 'status' => 'invalid_status', 'timestamp' => 1678886640, 'data_type' => 'image'], //Invalid status
//];
//$requiredFields = ['id', 'status', 'timestamp', 'data_type'];
// $validationErrors = validateMetadata($metadata, $requiredFields);
// if (empty($validationErrors)) {
// echo "Metadata is valid.\n";
// } else {
// echo "Validation errors:\n";
// foreach ($validationErrors as $error) {
// echo "Index: " . $error['index'] . ", Errors: " . implode(", ", $error['errors']) . "\n";
// }
// }
Add your comment