chill-bundles/src/Bundle/ChillMainBundle/Controller/GeographicalUnitByAddressApiController.php

50 lines
2.0 KiB
PHP

<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Controller;
use Chill\MainBundle\Entity\Address;
use Chill\MainBundle\Pagination\PaginatorFactory;
use Chill\MainBundle\Repository\GeographicalUnitRepositoryInterface;
use Chill\MainBundle\Serializer\Model\Collection;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\SerializerInterface;
class GeographicalUnitByAddressApiController
{
public function __construct(private readonly PaginatorFactory $paginatorFactory, private readonly GeographicalUnitRepositoryInterface $geographicalUnitRepository, private readonly Security $security, private readonly SerializerInterface $serializer) {}
#[Route(path: '/api/1.0/main/geographical-unit/by-address/{id}.{_format}', requirements: ['_format' => 'json'])]
public function getGeographicalUnitCoveringAddress(Address $address): JsonResponse
{
if (!$this->security->isGranted('ROLE_USER')) {
throw new AccessDeniedHttpException();
}
$count = $this->geographicalUnitRepository->countGeographicalUnitContainingAddress($address);
$pagination = $this->paginatorFactory->create($count);
$units = $this->geographicalUnitRepository->findGeographicalUnitContainingAddress($address, $pagination->getCurrentPageFirstItemNumber(), $pagination->getItemsPerPage());
$collection = new Collection($units, $pagination);
return new JsonResponse(
$this->serializer->serialize($collection, 'json', [AbstractNormalizer::GROUPS => ['read']]),
JsonResponse::HTTP_OK,
[],
true
);
}
}