<?php
declare(strict_types=1);
namespace App\Application\Controller;
use App\Application\Messenger\ErrorResponseBuilder;
use App\Application\Service\CacheService;
use JsonException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Annotation\Route;
class TranslationController extends AbstractController
{
public function __construct(
ErrorResponseBuilder $errorResponseBuilder,
MessageBusInterface $commandBus,
MessageBusInterface $queryBus,
private readonly string $frontTranslationsDir,
private readonly CacheService $cacheService,
) {
parent::__construct($errorResponseBuilder, $commandBus, $queryBus);
}
/**
* @throws JsonException
*/
#[Route('/api/translations/{locale}')]
public function index(string $locale): JsonResponse
{
$filePath = "{$this->frontTranslationsDir}/$locale.json";
if (!file_exists($filePath)) {
throw new NotFoundHttpException(sprintf('Translation file for locale "%s" not found', $locale));
}
$content = file_get_contents($filePath);
$response = new JsonResponse(json_decode($content, true, 512, JSON_THROW_ON_ERROR));
$response->headers->set('Content-Encoding', 'gzip');
$response->setContent(gzencode($response->getContent(), 9));
$this->cacheService->getCacheHeaders(["/translations/$locale"], $response->headers);
return $response;
}
}