<?php
/**
* Normalizes metadata data for scheduled runs with defensive checks.
*
* @param array $metadata The input metadata array.
* @return array The normalized metadata array, or an empty array on error.
*/
function normalizeMetadata(array $metadata): array
{
// Defensive check: Ensure input is an array
if (!is_array($metadata)) {
error_log("normalizeMetadata: Invalid input - expected array.");
return [];
}
$normalizedMetadata = [];
foreach ($metadata as $key => $value) {
// Defensive check: Ensure key is a string
if (!is_string($key)) {
error_log("normalizeMetadata: Invalid key type - expected string. Key: " . $key);
continue; // Skip invalid key
}
// Defensive check: Ensure value is not null or undefined
if ($value === null || $value === undefined) {
error_log("normalizeMetadata: Invalid value - cannot be null or undefined. Key: " . $key);
$normalizedMetadata[$key] = null; // or skip, depending on requirements
continue;
}
// Normalize data types: attempt to cast to string, integer, or float
$normalizedValue = $value;
//Try to cast to string
if (!is_string($normalizedValue)) {
$normalizedValue = (string)$normalizedValue;
}
//Try to cast to integer
if (!is_int($normalizedValue) && is_numeric($normalizedValue)) {
$normalizedValue = (int)$normalizedValue;
}
//Try to cast to float
if (!is_float($normalizedValue) && is_numeric($normalizedValue)) {
$normalizedValue = (float)$normalizedValue;
}
$normalizedMetadata[$key] = $normalizedValue;
}
return $normalizedMetadata;
}
//Example usage & testing
if (count($argv) > 1) {
$inputData = json_decode($argv[1], true);
$normalizedData = normalizeMetadata($inputData);
if (!empty($normalizedData)) {
echo json_encode($normalizedData, JSON_PRETTY_PRINT) . PHP_EOL;
} else {
echo "Normalization failed." . PHP_EOL;
}
} else {
$testData = [
"timestamp" => "2023-10-27 10:00:00",
"count" => "123",
"value" => 3.14,
"flag" => true,
"description" => null,
"invalidKey" => 123
];
$normalizedData = normalizeMetadata($testData);
echo json_encode($normalizedData, JSON_PRETTY_PRINT) . PHP_EOL;
}
?>
Add your comment