1. <?php
  2. /**
  3. * Flags anomalies in JSON payloads based on hard-coded limits.
  4. *
  5. * @param string $jsonPayload The JSON payload to validate.
  6. * @return array An array of flagged anomalies. Empty array if no anomalies found.
  7. */
  8. function flagJsonAnomalies(string $jsonPayload): array
  9. {
  10. $anomalies = [];
  11. $data = json_decode($jsonPayload, true);
  12. if ($data === null) {
  13. $anomalies[] = ['error' => 'Invalid JSON format'];
  14. return $anomalies;
  15. }
  16. // Hard-coded limits (example values - adjust as needed)
  17. $max_items = 10;
  18. $max_string_length = 255;
  19. $allowed_fields = ['id', 'name', 'value']; // Example: Allowed fields
  20. // Check for excessive number of items
  21. if (is_array($data) && count($data) > $max_items) {
  22. $anomalies[] = ['type' => 'items_count', 'value' => count($data), 'limit' => $max_items];
  23. }
  24. // Check for string lengths
  25. foreach ($data as $key => $value) {
  26. if (is_string($value) && strlen($value) > $max_string_length) {
  27. $anomalies[] = ['type' => 'string_length', 'field' => $key, 'value' => strlen($value), 'limit' => $max_string_length];
  28. }
  29. }
  30. //Check allowed fields
  31. if(is_array($data)){
  32. foreach($data as $key => $value){
  33. if(!in_array($key, $allowed_fields)){
  34. $anomalies[] = ['type' => 'unallowed_field', 'field' => $key, 'value' => $value, 'allowed' => $allowed_fields];
  35. }
  36. }
  37. }
  38. return $anomalies;
  39. }
  40. //Example Usage (replace with your actual JSON payload)
  41. //$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}]';
  42. // $anomalies = flagJsonAnomalies($jsonPayload);
  43. // print_r($anomalies);
  44. ?>

Add your comment