<?php
/**
* Flags anomalies in JSON payloads based on hard-coded limits.
*
* @param string $jsonPayload The JSON payload to validate.
* @return array An array of flagged anomalies. Empty array if no anomalies found.
*/
function flagJsonAnomalies(string $jsonPayload): array
{
$anomalies = [];
$data = json_decode($jsonPayload, true);
if ($data === null) {
$anomalies[] = ['error' => 'Invalid JSON format'];
return $anomalies;
}
// Hard-coded limits (example values - adjust as needed)
$max_items = 10;
$max_string_length = 255;
$allowed_fields = ['id', 'name', 'value']; // Example: Allowed fields
// Check for excessive number of items
if (is_array($data) && count($data) > $max_items) {
$anomalies[] = ['type' => 'items_count', 'value' => count($data), 'limit' => $max_items];
}
// Check for string lengths
foreach ($data as $key => $value) {
if (is_string($value) && strlen($value) > $max_string_length) {
$anomalies[] = ['type' => 'string_length', 'field' => $key, 'value' => strlen($value), 'limit' => $max_string_length];
}
}
//Check allowed fields
if(is_array($data)){
foreach($data as $key => $value){
if(!in_array($key, $allowed_fields)){
$anomalies[] = ['type' => 'unallowed_field', 'field' => $key, 'value' => $value, 'allowed' => $allowed_fields];
}
}
}
return $anomalies;
}
//Example Usage (replace with your actual JSON payload)
//$jsonPayload = '[{"id": 1, "name": "Product A", "value": 100}, {"id": 2, "name": "Product B", "value": 200}, {"id": 3, "name": "Product C", "value": 300}, {"id": 4, "name": "Product D", "value": 400}, {"id": 5, "name": "Product E", "value": 500}, {"id": 6, "name": "Product F", "value": 600}, {"id": 7, "name": "Product G", "value": 700}, {"id": 8, "name": "Product H", "value": 800}, {"id": 9, "name": "Product I", "value": 900}, {"id": 10, "name": "Product J", "value": 1000}, {"id": 11, "name": "Product K", "value": 1100}]';
// $anomalies = flagJsonAnomalies($jsonPayload);
// print_r($anomalies);
?>
Add your comment