<?php
declare(strict_types=1);
namespace App\Controller\Action;
use App\Service\GeoIPService;
use Sylius\Component\Order\Context\CartContextInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Intl\Countries;
use Twig\Environment;
class GeolocalisationControllerAction extends AbstractController
{
public function __construct(private CartContextInterface $cartContext, private Environment $twig, private GeoIPService $geoIPService, private RepositoryInterface $countryRepository)
{
}
public function __invoke(Request $request): Response
{
$cart = $this->cartContext->getCart();
$countryCode = null;
$countries = $this->countryRepository->findBy(['enabled' => true]);
$countryName = null;
if (null === $cart->getShippingAddress()) {
$ip = $request->getClientIp();
$countryCode = $this->geoIPService->getCountryCode($ip);
$countryName = Countries::getName($countryCode, 'fr');
}
return new Response($this->twig->render("@SyliusShop/_geolocalisation.html.twig", [
'countryCode' => $countryCode,
'countries' => $countries,
'countryName' => $countryName
]));
}
}