<?php
namespace App\Controller;
use App\Entity\Location\City;
use App\Entity\Profile\Genders;
use App\Entity\Profile\Profile;
use App\Repository\ProfileRepository;
use App\Service\DefaultCityProvider;
use App\Service\ProfileList;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\RouterInterface;
class RecentProfilesController extends AbstractController
{
const DEFAULT_MAX_ENTRIES = 3;
private Request $request;
public function __construct(
RequestStack $requestStack,
private DefaultCityProvider $defaultCityProvider,
private RouterInterface $router,
private ProfileList $profileList,
private ProfileRepository $profileRepository,
)
{
$this->request = $requestStack->getCurrentRequest();
}
#[Route("/recently-viewed", name: "recent_profiles.recently_viewed.list", methods: ["POST"])]
public function recentlyViewedList(): Response
{
if(false === $this->request->isXmlHttpRequest()) {
throw new BadRequestHttpException();
}
$data = $this->request->getContent();
$data = json_decode($data, true);
$profiles = $data['recently_viewed_profiles'] ?? [];
$profiles = $this->profileRepository->findByIds($profiles);
return $this->render('RecentProfiles/recently_viewed.list.html.twig', [
'profiles' => $profiles,
]);
}
#[Route("/{city}/{count}/{gender}", name: "recent_profiles.list", methods: ["POST"], defaults: ["gender" => 1])]
#[ParamConverter("city", converter:"city_converter")]
public function list(City $city, int $count = self::DEFAULT_MAX_ENTRIES, int $gender = Genders::FEMALE): Response
{
$genders = ($gender == Genders::FEMALE) ? [Genders::FEMALE] : [/*Genders::FEMALE, */$gender];
$city = $this->request->get('city') ?? $this->defaultCityProvider->getDefaultCity();
$locale = $this->request->get('locale') ?? 'ru';
$result = $this->profileList->listRecent($city, $count, $genders);
$profiles = array_map(function(Profile $profile) use ($locale): array {
return [
'name' => $profile->getName()->getTranslation($locale),
'uri' => $this->router->generate('profile_preview.page', ['city' => $profile->getCity()->getUriIdentity(), 'profile' => $profile->getUriIdentity()]),
];
}, $result);
return new JsonResponse($profiles);
}
}