<?php
namespace App\Controller;
use App\Entity\Location\City;
use App\Entity\Profile\Genders;
use App\Service\ProfileList;
use App\Service\ProfileListSpecificationService;
use App\Specification\Profile\ProfileIdNotIn;
use Happyr\DoctrineSpecification\Logic\AndX;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Cache\ItemInterface;
class ProfileWidgetController extends AbstractController
{
const CACHE_ITEM_KEY_LIST_BY_CATEGORIES = 'list_by_categories';
#[Route(path: '/by-categories/', name: 'profile_widget.by_categories')]
public function listByCategories(
City $city, ProfileListSpecificationService $profileListSpecificationService, ProfileList $profileList, CacheItemPoolInterface $profileWidgetCache
): Response
{
$profilesByCategories = $profileWidgetCache->get(
self::CACHE_ITEM_KEY_LIST_BY_CATEGORIES,
function (ItemInterface $item) use ($city, $profileListSpecificationService, $profileList) {
$categories = ['elite', 'approved', 'new'];
$profilesByCategories = [];
$profilesIds = [];
$limit = 6;
foreach ($categories as $category) {
$spec = match ($category) {
'elite' => $profileListSpecificationService->listForEliteGirls($city),
'approved' => $profileListSpecificationService->listApproved(),
'new' => $profileListSpecificationService->listNew(),
'default' => null,
};
if(null === $spec) {
continue;
}
$spec = $spec->spec();
$specWithExclusion = count($profilesIds) ? new AndX($spec, new ProfileIdNotIn($profilesIds)) : $spec;
$profiles = $profileList->listRandom($city, null, $specWithExclusion, null, true, null, [Genders::FEMALE], false, $limit);
if(count($profiles) < $limit && $specWithExclusion !== $spec) {
$profiles = $profileList->listRandom($city, null, $spec, null, true, null, [Genders::FEMALE], false, $limit);
}
$profilesByCategories[$category] = $profiles;
foreach ($profiles as $profile) {
$profilesIds[] = $profile->id;
}
}
return $profilesByCategories;
}
);
return $this->render('ProfileWidget/list_by_categories/widget.html.twig', [
'profiles_by_categories' => $profilesByCategories,
]);
}
}