src/Menu/CityListMenuBuilder.php line 36

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by simpson <simpsonwork@gmail.com>
  4.  * Date: 2019-03-20
  5.  * Time: 10:04
  6.  */
  7. namespace App\Menu;
  8. use App\Repository\CityRepository;
  9. use App\Repository\ProfileRepository;
  10. use Knp\Menu\FactoryInterface;
  11. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  12. use Symfony\Component\HttpFoundation\RequestStack;
  13. use Symfony\Component\Intl\Countries;
  14. use Symfony\Contracts\Translation\TranslatorInterface;
  15. class CityListMenuBuilder
  16. {
  17.     const NAME 'city_list';
  18.     private string $defaultCity;
  19.     public function __construct(
  20.         protected FactoryInterface $factory,
  21.         protected RequestStack $requestStack,
  22.         ParameterBagInterface $parameterBag,
  23.         protected CityRepository $cityRepository,
  24.         protected ProfileRepository $profileRepository,
  25.         protected TranslatorInterface $translator
  26.     )
  27.     {
  28.         $this->defaultCity = (string)$parameterBag->get('default_city');
  29.     }
  30.     public function build(array $options)
  31.     {
  32.         $countries Countries::getNames($this->getLocale());
  33.         $countByCity $this->profileRepository->countByCity();
  34.         $menu $this->factory->createItem(self::NAME);
  35.         foreach ($this->cityRepository->findAll() as $city) {
  36.             $countryCode $city->getCountryCode();
  37.             $country $countries[$countryCode];
  38.             if (!isset($menu[$country])) {
  39.                 $menu->addChild($country);
  40.             }
  41.             if ($city->equals($this->defaultCity)) {
  42.                 $options = [
  43.                     'route' => 'homepage',
  44.                 ];
  45.             } else {
  46.                 $options = [
  47.                     'route'           => 'profile_list.list_by_city',
  48.                     'routeParameters' => ['city' => $city->getUriIdentity()],
  49.                 ];
  50.             }
  51.             $label sprintf('%s (%d)'$this->translator->trans($city->getName()), $countByCity[$city->getId()] ?? 0);
  52.             $menu[$country]->addChild($label$options);
  53.         }
  54.         return $menu;
  55.     }
  56.     protected function getLocale(): string
  57.     {
  58.         $request $this->requestStack->getCurrentRequest();
  59.         return $request->getLocale();
  60.     }
  61. }