Add Symfony payload mapping, fixtures, and QA tooling
This commit is contained in:
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controller;
|
||||
|
||||
use App\Dto\SignalPayload;
|
||||
use App\Entity\Signal;
|
||||
use App\Repository\SignalRepository;
|
||||
use App\Service\SignalSnapshotBuilder;
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
use Symfony\Component\HttpFoundation\JsonResponse;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpKernel\Attribute\MapQueryParameter;
|
||||
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
|
||||
use Symfony\Component\Routing\Annotation\Route;
|
||||
|
||||
#[Route(path: '/api/signals')]
|
||||
class SignalController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SignalRepository $signals,
|
||||
private readonly SignalSnapshotBuilder $snapshotBuilder,
|
||||
) {
|
||||
}
|
||||
|
||||
#[Route(path: '', name: 'api_signals_index', methods: ['GET'])]
|
||||
public function index(Request $request, #[MapQueryParameter('limit', flags: FILTER_NULL_ON_FAILURE)] ?int $limit = null): JsonResponse
|
||||
{
|
||||
$limit = $this->normalizeLimit($limit);
|
||||
|
||||
$clientKey = $this->hashIp($this->extractClientIp($request));
|
||||
|
||||
$signals = $this->signals->findRecent($limit);
|
||||
$snapshot = $this->snapshotBuilder->build($signals);
|
||||
|
||||
$payload = [
|
||||
'clientKey' => $clientKey,
|
||||
'points' => $snapshot['points'],
|
||||
'density' => $snapshot['density'],
|
||||
'latestByUser' => $snapshot['latestByUser'],
|
||||
'totals' => $snapshot['totals'],
|
||||
'updatedAt' => new DateTimeImmutable('now', new DateTimeZone('UTC'))->format(DATE_ATOM),
|
||||
];
|
||||
|
||||
return new JsonResponse($payload);
|
||||
}
|
||||
|
||||
#[Route(path: '', name: 'api_signals_store', methods: ['POST'])]
|
||||
public function store(#[MapRequestPayload(validationFailedStatusCode: JsonResponse::HTTP_UNPROCESSABLE_ENTITY)] SignalPayload $payload, Request $request): JsonResponse
|
||||
{
|
||||
$lat = $payload->lat;
|
||||
$lng = $payload->lng;
|
||||
|
||||
if (! is_finite($lat) || ! is_finite($lng)) {
|
||||
return $this->errorResponse('invalid_coordinates', 'Latitude and longitude must be numbers.', JsonResponse::HTTP_UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
|
||||
if ($lat < -90 || $lat > 90 || $lng < -180 || $lng > 180) {
|
||||
return $this->errorResponse('out_of_bounds', 'Latitude or longitude out of range.', JsonResponse::HTTP_UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
|
||||
$clientIp = $this->extractClientIp($request);
|
||||
$clientKey = $this->hashIp($clientIp);
|
||||
|
||||
$signal = new Signal()
|
||||
->setUserKey($clientKey)
|
||||
->setLat($lat)
|
||||
->setLng($lng)
|
||||
->setCreatedAt(new DateTimeImmutable('now', new DateTimeZone('UTC')));
|
||||
|
||||
$this->signals->save($signal);
|
||||
|
||||
return new JsonResponse([
|
||||
'status' => 'stored',
|
||||
'clientKey' => $clientKey,
|
||||
'point' => [
|
||||
'id' => $signal->getId(),
|
||||
'lat' => $signal->getLat(),
|
||||
'lng' => $signal->getLng(),
|
||||
'createdAt' => $signal->getCreatedAt()->format(DATE_ATOM),
|
||||
'userKey' => $signal->getUserKey(),
|
||||
],
|
||||
], JsonResponse::HTTP_CREATED);
|
||||
}
|
||||
|
||||
private function errorResponse(string $error, string $message, int $statusCode): JsonResponse
|
||||
{
|
||||
return new JsonResponse([
|
||||
'error' => $error,
|
||||
'message' => $message,
|
||||
], $statusCode);
|
||||
}
|
||||
|
||||
private function normalizeLimit(?int $limit): int
|
||||
{
|
||||
$limit ??= 750;
|
||||
if ($limit < 1 || $limit > 5000) {
|
||||
return 750;
|
||||
}
|
||||
|
||||
return $limit;
|
||||
}
|
||||
|
||||
private function extractClientIp(Request $request): string
|
||||
{
|
||||
$forwarded = $request->headers->get('X-Forwarded-For');
|
||||
if ($forwarded !== null && $forwarded !== '') {
|
||||
$parts = array_filter(array_map('trim', explode(',', $forwarded)));
|
||||
if ($parts !== []) {
|
||||
return $parts[0];
|
||||
}
|
||||
}
|
||||
|
||||
return $request->getClientIp() ?? '0.0.0.0';
|
||||
}
|
||||
|
||||
private function hashIp(string $ip): string
|
||||
{
|
||||
return substr(hash('sha256', $ip), 0, 12);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\DataFixtures;
|
||||
|
||||
use Doctrine\Bundle\FixturesBundle\Fixture;
|
||||
use Doctrine\Persistence\ObjectManager;
|
||||
|
||||
class AppFixtures extends Fixture
|
||||
{
|
||||
public function load(ObjectManager $manager): void
|
||||
{
|
||||
// $product = new Product();
|
||||
// $manager->persist($product);
|
||||
|
||||
$manager->flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\DataFixtures;
|
||||
|
||||
use App\Entity\Signal;
|
||||
use DateInterval;
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
use Doctrine\Bundle\FixturesBundle\Fixture;
|
||||
use Doctrine\Persistence\ObjectManager;
|
||||
|
||||
class SignalFixtures extends Fixture
|
||||
{
|
||||
public function load(ObjectManager $manager): void
|
||||
{
|
||||
$baseTime = new DateTimeImmutable('2024-08-01 12:00:00', new DateTimeZone('UTC'));
|
||||
$coordinates = [
|
||||
[
|
||||
'user' => 'user-alpha',
|
||||
'lat' => -11.6877,
|
||||
'lng' => 27.5026,
|
||||
'offset' => 0,
|
||||
],
|
||||
[
|
||||
'user' => 'user-beta',
|
||||
'lat' => -11.6895,
|
||||
'lng' => 27.5081,
|
||||
'offset' => 3,
|
||||
],
|
||||
[
|
||||
'user' => 'user-alpha',
|
||||
'lat' => -11.6852,
|
||||
'lng' => 27.4974,
|
||||
'offset' => 6,
|
||||
],
|
||||
];
|
||||
|
||||
foreach ($coordinates as $config) {
|
||||
$signal = new Signal()
|
||||
->setUserKey($config['user'])
|
||||
->setLat($config['lat'])
|
||||
->setLng($config['lng'])
|
||||
->setCreatedAt($baseTime->add(new DateInterval(sprintf('PT%dM', $config['offset']))));
|
||||
|
||||
$manager->persist($signal);
|
||||
}
|
||||
|
||||
$manager->flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Dto;
|
||||
|
||||
final readonly class SignalPayload
|
||||
{
|
||||
public function __construct(
|
||||
public float $lat,
|
||||
public float $lng,
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Entity;
|
||||
|
||||
use App\Repository\SignalRepository;
|
||||
use DateTimeImmutable;
|
||||
use Doctrine\DBAL\Types\Types;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
|
||||
#[ORM\Entity(repositoryClass: SignalRepository::class)]
|
||||
#[ORM\Table(name: 'signals')]
|
||||
#[ORM\Index(columns: ['created_at'], name: 'idx_signals_created_at')]
|
||||
#[ORM\Index(columns: ['user_key'], name: 'idx_signals_user_key')]
|
||||
class Signal
|
||||
{
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column(type: Types::INTEGER)]
|
||||
private ?int $id = null; // @phpstan-ignore property.unusedType
|
||||
|
||||
#[ORM\Column(type: Types::STRING, length: 64)]
|
||||
private string $userKey;
|
||||
|
||||
#[ORM\Column(type: Types::FLOAT)]
|
||||
private float $lat;
|
||||
|
||||
#[ORM\Column(type: Types::FLOAT)]
|
||||
private float $lng;
|
||||
|
||||
#[ORM\Column(type: Types::DATETIME_IMMUTABLE, name: 'created_at')]
|
||||
private DateTimeImmutable $createdAt;
|
||||
|
||||
public function getId(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function getUserKey(): string
|
||||
{
|
||||
return $this->userKey;
|
||||
}
|
||||
|
||||
public function setUserKey(string $userKey): self
|
||||
{
|
||||
$this->userKey = $userKey;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getLat(): float
|
||||
{
|
||||
return $this->lat;
|
||||
}
|
||||
|
||||
public function setLat(float $lat): self
|
||||
{
|
||||
$this->lat = $lat;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getLng(): float
|
||||
{
|
||||
return $this->lng;
|
||||
}
|
||||
|
||||
public function setLng(float $lng): self
|
||||
{
|
||||
$this->lng = $lng;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getCreatedAt(): DateTimeImmutable
|
||||
{
|
||||
return $this->createdAt;
|
||||
}
|
||||
|
||||
public function setCreatedAt(DateTimeImmutable $createdAt): self
|
||||
{
|
||||
$this->createdAt = $createdAt;
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Repository;
|
||||
|
||||
use App\Entity\Signal;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
/**
|
||||
* @extends ServiceEntityRepository<Signal>
|
||||
*/
|
||||
class SignalRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, Signal::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<Signal>
|
||||
*/
|
||||
public function findRecent(int $limit): array
|
||||
{
|
||||
return $this->createQueryBuilder('signal')
|
||||
->orderBy('signal.createdAt', 'DESC')
|
||||
->setMaxResults($limit)
|
||||
->getQuery()
|
||||
->getResult();
|
||||
}
|
||||
|
||||
public function save(Signal $signal): void
|
||||
{
|
||||
$entityManager = $this->getEntityManager();
|
||||
$entityManager->persist($signal);
|
||||
$entityManager->flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Entity\Signal;
|
||||
|
||||
class SignalSnapshotBuilder
|
||||
{
|
||||
/**
|
||||
* @param list<Signal> $signals
|
||||
*
|
||||
* @return array{
|
||||
* points: list<array{id: int, lat: float, lng: float, createdAt: string, userKey: string}>,
|
||||
* density: list<array{lat: float, lng: float, intensity: int}>,
|
||||
* latestByUser: list<array{id: int, lat: float, lng: float, createdAt: string, userKey: string}>,
|
||||
* totals: array{points: int, contributors: int}
|
||||
* }
|
||||
*/
|
||||
public function build(array $signals): array
|
||||
{
|
||||
$points = [];
|
||||
$densityBuckets = [];
|
||||
$latestByUser = [];
|
||||
|
||||
foreach ($signals as $signal) {
|
||||
$point = [
|
||||
'id' => (int) $signal->getId(),
|
||||
'lat' => $signal->getLat(),
|
||||
'lng' => $signal->getLng(),
|
||||
'createdAt' => $signal->getCreatedAt()->format(DATE_ATOM),
|
||||
'userKey' => $signal->getUserKey(),
|
||||
];
|
||||
|
||||
$points[] = $point;
|
||||
|
||||
$bucketLat = round($signal->getLat(), 3);
|
||||
$bucketLng = round($signal->getLng(), 3);
|
||||
$bucketKey = $bucketLat . ':' . $bucketLng;
|
||||
|
||||
if (! isset($densityBuckets[$bucketKey])) {
|
||||
$densityBuckets[$bucketKey] = [
|
||||
'lat' => $bucketLat,
|
||||
'lng' => $bucketLng,
|
||||
'intensity' => 0,
|
||||
'latestPoint' => $point,
|
||||
];
|
||||
}
|
||||
|
||||
$densityBuckets[$bucketKey]['intensity']++;
|
||||
if ($point['createdAt'] > $densityBuckets[$bucketKey]['latestPoint']['createdAt']) {
|
||||
$densityBuckets[$bucketKey]['latestPoint'] = $point;
|
||||
}
|
||||
|
||||
$existingLatest = $latestByUser[$point['userKey']] ?? null;
|
||||
if ($existingLatest === null || $point['createdAt'] > $existingLatest['createdAt']) {
|
||||
$latestByUser[$point['userKey']] = $point;
|
||||
}
|
||||
}
|
||||
|
||||
usort($points, static fn (array $a, array $b): int => strcmp($b['createdAt'], $a['createdAt']));
|
||||
|
||||
$density = array_values(array_map(
|
||||
static fn (array $bucket): array => [
|
||||
'lat' => $bucket['lat'],
|
||||
'lng' => $bucket['lng'],
|
||||
'intensity' => $bucket['intensity'],
|
||||
],
|
||||
$densityBuckets,
|
||||
));
|
||||
|
||||
usort($density, static fn (array $a, array $b): int => $b['intensity'] <=> $a['intensity']);
|
||||
|
||||
$latest = array_values($latestByUser);
|
||||
usort($latest, static fn (array $a, array $b): int => strcmp($b['createdAt'], $a['createdAt']));
|
||||
|
||||
return [
|
||||
'points' => $points,
|
||||
'density' => $density,
|
||||
'latestByUser' => $latest,
|
||||
'totals' => [
|
||||
'points' => count($points),
|
||||
'contributors' => count($latestByUser),
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user