<?php
namespace App\Menu;
use App\Entity\Location\City;
use App\Service\DefaultCityProvider;
use App\Service\EntitySortService;
use App\Service\LocationsProfileCounters;
use Knp\Menu\FactoryInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Contracts\Translation\TranslatorInterface;
class LocationsCountersMenuBuilder
{
const NAME = 'locations_counters';
public function __construct(
private FactoryInterface $factory,
private RequestStack $requestStack,
private DefaultCityProvider $defaultCityProvider,
private TranslatorInterface $translator,
private EntitySortService $sortService,
private LocationsProfileCounters $locationsProfileCounters,
) {}
public function build(array $options)
{
$menu = $this->factory->createItem(self::NAME);
$currentCity = $this->getCurrentCity();
$stationsItem = $menu->addChild('stations');
$countByStations = $this->locationsProfileCounters->getCountByStations();
$stations = $currentCity->getStations();
$stations = $this->sortService->sortEntityArrayByTranslatableFieldName(iterator_to_array($stations->getIterator()), 'name');
foreach ($stations as $station) {
$label = sprintf('%s (%d)', $this->translator->trans($station->getName()), $countByStations[$station->getId()] ?? 0);
$stationsItem->addChild($label, [
'route' => 'profile_list.list_by_station',
'routeParameters' => [
'city' => $currentCity->getUriIdentity(),
'station' => $station->getUriIdentity(),
],
]);
}
$districtsItem = $menu->addChild('districts');
$countByDistricts = $this->locationsProfileCounters->getCountByDistricts();
$districts = $currentCity->getDistricts();
$districts = $this->sortService->sortEntityArrayByTranslatableFieldName(iterator_to_array($districts->getIterator()), 'name');
foreach ($districts as $district) {
$label = sprintf('%s (%d)', $this->translator->trans($district->getName()), $countByDistricts[$district->getId()] ?? 0);
$districtsItem->addChild($label, [
'route' => 'profile_list.list_by_district',
'routeParameters' => [
'city' => $currentCity->getUriIdentity(),
'district' => $district->getUriIdentity(),
],
]);
}
$countiesItem = $menu->addChild('counties');
$countByCounties = $this->locationsProfileCounters->getCountByCounties();
$counties = $currentCity->getCounties();
$counties = $this->sortService->sortEntityArrayByTranslatableFieldName(iterator_to_array($counties->getIterator()), 'name');
foreach ($counties as $county) {
$label = sprintf('%s (%d)', $this->translator->trans($county->getName()), $countByCounties[$county->getId()] ?? 0);
$countiesItem->addChild($label, [
'route' => 'profile_list.list_by_county',
'routeParameters' => [
'city' => $currentCity->getUriIdentity(),
'county' => $county->getUriIdentity(),
],
]);
}
return $menu;
}
private function getCurrentCity(): City
{
$request = $this->requestStack->getCurrentRequest();
$city = $request->attributes->get('city');
if (null === $city) {
$city = $this->defaultCityProvider->getDefaultCity();
}
return $city;
}
}