diff --git a/cloud/src/Ingest/EventValidator.php b/cloud/src/Ingest/EventValidator.php new file mode 100644 index 0000000..a119935 --- /dev/null +++ b/cloud/src/Ingest/EventValidator.php @@ -0,0 +1,40 @@ + 3) $errors[] = 'too_many:snapshots'; + else foreach ($snaps as $s) if (!is_string($s)) { $errors[] = 'bad:snapshot_item'; break; } + + if ($errors) return ['ok' => false, 'errors' => $errors, 'clean' => []]; + + $clean = [ + 'device_id' => (string)$p['device_id'], + 'camera_id' => (string)$p['camera_id'], + 'event_type' => (string)$p['event_type'], + 'severity' => (string)$p['severity'], + 'track_id' => isset($p['track_id']) ? (int)$p['track_id'] : null, + 'zone_id' => isset($p['zone_id']) ? (string)$p['zone_id'] : null, + 'occurred_at' => (float)$p['occurred_at'], + 'duration_s' => (float)($p['duration_s'] ?? 0.0), + 'metrics' => is_array($p['metrics'] ?? null) ? $p['metrics'] : [], + ]; + return ['ok' => true, 'errors' => [], 'clean' => $clean]; + } +} diff --git a/cloud/tests/EventValidatorTest.php b/cloud/tests/EventValidatorTest.php new file mode 100644 index 0000000..0bcfcca --- /dev/null +++ b/cloud/tests/EventValidatorTest.php @@ -0,0 +1,34 @@ + 'pi-1', 'camera_id' => 'cam-1', 'event_type' => 'fall', + 'severity' => 'high', 'occurred_at' => 1000.0, 'snapshots' => ['aGk=']]; + } + public function testAcceptsValid(): void { + $r = EventValidator::validate($this->valid()); + $this->assertTrue($r['ok'], implode(',', $r['errors'])); + $this->assertSame('fall', $r['clean']['event_type']); + } + public function testRejectsUnknownEventType(): void { + $p = $this->valid(); $p['event_type'] = 'explode'; + $this->assertFalse(EventValidator::validate($p)['ok']); + } + public function testRejectsUnknownSeverity(): void { + $p = $this->valid(); $p['severity'] = 'ULTRA'; + $this->assertFalse(EventValidator::validate($p)['ok']); + } + public function testRejectsMissingRequired(): void { + $p = $this->valid(); unset($p['device_id']); + $this->assertFalse(EventValidator::validate($p)['ok']); + } + public function testRejectsTooManySnapshots(): void { + $p = $this->valid(); $p['snapshots'] = ['a', 'b', 'c', 'd']; + $this->assertFalse(EventValidator::validate($p)['ok']); + } +}