<?php
/**
* Created by simpson <simpsonwork@gmail.com>
* Date: 2019-03-21
* Time: 21:24
*/
namespace App\Menu;
use App\Entity\Location\City;
use App\Repository\ReadModel\StationLineReadModel;
use App\Repository\StationRepository;
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 CityStationsMenuBuilder
{
const NAME = 'city_stations';
public function __construct(
private FactoryInterface $factory,
private RequestStack $requestStack,
private DefaultCityProvider $defaultCityProvider,
private TranslatorInterface $translator,
private EntitySortService $sortService,
private StationRepository $stationRepository,
private LocationsProfileCounters $locationsProfileCounters,
) {}
public function build(array $options)
{
$countByStations = $this->locationsProfileCounters->getCountByStations();
$menu = $this->factory->createItem(self::NAME);
$currentCity = $this->getCurrentCity();
if ($currentCity->equals($this->defaultCityProvider->getDefaultCity())) {
$options = [
'route' => 'homepage',
];
} else {
$options = [
'route' => 'profile_list.list_by_city',
'routeParameters' => ['city' => $currentCity->getUriIdentity()],
];
}
$menu->addChild('all_stations', $options);
$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);
$menu->addChild($label, [
'route' => 'profile_list.list_by_station',
'routeParameters' => [
'city' => $currentCity->getUriIdentity(),
'station' => $station->getUriIdentity(),
],
'extras' => [
'lines' => array_map(function(StationLineReadModel $line): array { return [
'name' => $line->name,
'color' => $line->color,
]; }, $this->stationRepository->stationLinesCached($station)),
],
]);
}
return $menu;
}
private function getCurrentCity(): City
{
$request = $this->requestStack->getCurrentRequest();
$city = $request->attributes->get('city');
if (null === $city) {
$city = $this->defaultCityProvider->getDefaultCity();
}
return $city;
}
}