<?php
/**
* Created by simpson <simpsonwork@gmail.com>
* Date: 2019-03-20
* Time: 10:04
*/
namespace App\Menu;
use App\Repository\CityRepository;
use App\Repository\ProfileRepository;
use Knp\Menu\FactoryInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Intl\Countries;
use Symfony\Contracts\Translation\TranslatorInterface;
class CityListMenuBuilder
{
const NAME = 'city_list';
private string $defaultCity;
public function __construct(
protected FactoryInterface $factory,
protected RequestStack $requestStack,
ParameterBagInterface $parameterBag,
protected CityRepository $cityRepository,
protected ProfileRepository $profileRepository,
protected TranslatorInterface $translator
)
{
$this->defaultCity = (string)$parameterBag->get('default_city');
}
public function build(array $options)
{
$countries = Countries::getNames($this->getLocale());
$countByCity = $this->profileRepository->countByCity();
$menu = $this->factory->createItem(self::NAME);
foreach ($this->cityRepository->findAll() as $city) {
$countryCode = $city->getCountryCode();
$country = $countries[$countryCode];
if (!isset($menu[$country])) {
$menu->addChild($country);
}
if ($city->equals($this->defaultCity)) {
$options = [
'route' => 'homepage',
];
} else {
$options = [
'route' => 'profile_list.list_by_city',
'routeParameters' => ['city' => $city->getUriIdentity()],
];
}
$label = sprintf('%s (%d)', $this->translator->trans($city->getName()), $countByCity[$city->getId()] ?? 0);
$menu[$country]->addChild($label, $options);
}
return $menu;
}
protected function getLocale(): string
{
$request = $this->requestStack->getCurrentRequest();
return $request->getLocale();
}
}