src/Component/Core/Shop/Controller/Map/MapIndexAction.php line 17

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace BitBag\OpenMarketplace\Component\Core\Shop\Controller\Map;
  4. use GeoIp2\Database\Reader;
  5. use Symfony\Component\HttpFoundation\RequestStack;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Twig\Environment;
  8. /**
  9.  * Renders the Hyfindr map page and resolves an initial map center from the
  10.  * visitor's IP (GeoLite2). Falls back to null (frontend default) for local /
  11.  * private IPs or when the lookup fails. Never throws on geoip errors.
  12.  */
  13. final class MapIndexAction
  14. {
  15.     private const TEMPLATE 'Context/HyfindrMap/index.html.twig';
  16.     public function __construct(
  17.         private Environment $twig,
  18.         private RequestStack $requestStack,
  19.         private Reader $geoIpReader,
  20.     ) {
  21.     }
  22.     public function __invoke(): Response
  23.     {
  24.         return new Response($this->twig->render(self::TEMPLATE, [
  25.             'initialCenter' => $this->resolveInitialCenter(),
  26.         ]));
  27.     }
  28.     /**
  29.      * @return array{0: float, 1: float}|null [longitude, latitude]
  30.      */
  31.     private function resolveInitialCenter(): ?array
  32.     {
  33.         $request $this->requestStack->getCurrentRequest();
  34.         if (null === $request) {
  35.             return null;
  36.         }
  37.         $ip $request->getClientIp();
  38.         if (null === $ip || !$this->isPublicIp($ip)) {
  39.             return null;
  40.         }
  41.         try {
  42.             $record $this->geoIpReader->city($ip);
  43.             $latitude $record->location->latitude;
  44.             $longitude $record->location->longitude;
  45.         } catch (\Throwable) {
  46.             return null;
  47.         }
  48.         if (null === $latitude || null === $longitude) {
  49.             return null;
  50.         }
  51.         return [(float) $longitude, (float) $latitude];
  52.     }
  53.     private function isPublicIp(string $ip): bool
  54.     {
  55.         return false !== filter_var(
  56.             $ip,
  57.             FILTER_VALIDATE_IP,
  58.             FILTER_FLAG_NO_PRIV_RANGE FILTER_FLAG_NO_RES_RANGE,
  59.         );
  60.     }
  61. }