<?php
namespace App;
use App\Entity\Chirp;
use Doctrine\ORM\AbstractQuery;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;
final class ChirpController
{
private const SCALAR_PROJECTION = 'c.id AS chirp_id, c.text AS chirp_text, c.createdAt AS chirp_created_at, c.updatedAt AS chirp_updated_at, a.id AS author_id, a.username AS author_username, a.createdAt AS author_created_at, a.updatedAt AS author_updated_at';
private readonly string $projection;
private readonly int $hydrationMode;
public function __construct(#[Autowire('%env(BENCHMARK_HYDRATION)%')] string $hydration)
{
if (!in_array($hydration, ['object', 'scalar'], true)) {
throw new \InvalidArgumentException('BENCHMARK_HYDRATION must be object or scalar.');
}
$this->projection = 'scalar' === $hydration ? self::SCALAR_PROJECTION : 'c, a';
$this->hydrationMode = 'scalar' === $hydration ? AbstractQuery::HYDRATE_SCALAR : AbstractQuery::HYDRATE_OBJECT;
}
#[Route('/up', methods: ['GET'])]
public function health(): JsonResponse
{
return new JsonResponse(['status' => 'ok']);
}
#[Route('/api/v1/chirps', methods: ['GET'])]
public function index(Request $request, EntityManagerInterface $em): JsonResponse
{
$page = max(1, $request->query->getInt('page', 1));
$total = $em->getRepository(Chirp::class)->count();
$last = max(1, (int) ceil($total / 50));
$rows = $em->createQuery('SELECT '.$this->projection.' FROM App\Entity\Chirp c JOIN c.author a ORDER BY c.id DESC')
->setFirstResult(($page - 1) * 50)->setMaxResults(50)->getResult($this->hydrationMode);
$path = '/api/v1/chirps';
$url = static fn (int $number): string => $path.'?page='.$number;
$links = [['url' => $page > 1 ? $url($page - 1) : null, 'label' => '« Previous', 'active' => false]];
for ($i = 1; $i <= $last; ++$i) {
$links[] = ['url' => $url($i), 'label' => (string) $i, 'active' => $i === $page];
}
$links[] = ['url' => $page < $last ? $url($page + 1) : null, 'label' => 'Next »', 'active' => false];
return new JsonResponse([
'current_page' => $page,
'data' => array_map(self::serializeChirp(...), $rows),
'first_page_url' => $url(1),
'from' => $rows ? ($page - 1) * 50 + 1 : null,
'last_page' => $last,
'last_page_url' => $url($last),
'links' => $links,
'next_page_url' => $page < $last ? $url($page + 1) : null,
'path' => $path,
'per_page' => 50,
'prev_page_url' => $page > 1 ? $url($page - 1) : null,
'to' => $rows ? ($page - 1) * 50 + count($rows) : null,
'total' => $total,
]);
}
#[Route('/api/v1/chirps/{id}', requirements: ['id' => '\d+'], methods: ['GET'])]
public function show(int $id, EntityManagerInterface $em): JsonResponse
{
$chirp = $em->createQuery('SELECT '.$this->projection.' FROM App\Entity\Chirp c JOIN c.author a WHERE c.id = :id')
->setParameter('id', $id)->getOneOrNullResult($this->hydrationMode);
return null !== $chirp ? new JsonResponse(self::serializeChirp($chirp)) : new JsonResponse(['message' => 'Not found'], 404);
}
private static function serializeChirp(Chirp|array $chirp): array
{
if ($chirp instanceof Chirp) {
return $chirp->toArray();
}
return [
'id' => (int) $chirp['chirp_id'],
'text' => $chirp['chirp_text'],
'author_id' => (int) $chirp['author_id'],
'created_at' => self::formatTimestamp($chirp['chirp_created_at']),
'updated_at' => self::formatTimestamp($chirp['chirp_updated_at']),
'author' => [
'id' => (int) $chirp['author_id'],
'username' => $chirp['author_username'],
'created_at' => self::formatTimestamp($chirp['author_created_at']),
'updated_at' => self::formatTimestamp($chirp['author_updated_at']),
],
];
}
private static function formatTimestamp(?string $timestamp): ?string
{
// The schema uses second-precision UTC timestamps. Preserve the entity JSON format.
return null === $timestamp ? null : str_replace(' ', 'T', $timestamp).'.000000Z';
}
}