<?php
namespace Rawafed\CommonsBundle\Service;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;
class LocationManager
{
private $requestStack;
private $tokenStorage;
private $authorizationChecker;
private $countryCode = null;
public function __construct(RequestStack $requestStack, TokenStorageInterface $tokenStorage, AuthorizationChecker $authorizationChecker)
{
$this->requestStack = $requestStack;
$this->tokenStorage = $tokenStorage;
$this->authorizationChecker = $authorizationChecker;
}
public function getCountryCode()
{
$request = $this->requestStack->getMasterRequest();
if ($request && $request->query->has('__country')) {
$this->countryCode = $request->query->get('__country');
} elseif ($request && $request->cookies->get('__country')) {
$this->countryCode = $request->cookies->get('__country');
} elseif (!$this->countryCode) {
$token = $this->tokenStorage->getToken();
if ($token && $this->authorizationChecker->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
$user = $token->getUser();
if (method_exists($user->getUserProfile(), 'getCountry')) {
$userCountry = $user->getUserProfile()->getCountry();
if ($userCountry) {
$this->countryCode = $userCountry->getId();
}
}
}
if (!$this->countryCode) {
$ip = $request->getClientIp();
if (class_exists('\GeoIp2\Database\Reader')) {
$reader = new \GeoIp2\Database\Reader(__DIR__ . '/../../../../src/Resources/geodb/GeoLite2-Country.mmdb');
try {
$record = $reader->country($ip);
$this->countryCode = $record->country->isoCode;
} catch (\GeoIp2\Exception\AddressNotFoundException $ex) {
}
} else {
throw new \Exception('GeoIp2 reader class is not found. Add "geoip2/geoip2" to composer.json');
}
// During development:
if ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') {
$this->countryCode = 'SA';
}
}
}
if (!$this->countryCode) {
$this->countryCode = 'WW';
} elseif ($this->countryCode == 'IL') {
$this->countryCode = 'PS';
} elseif ($this->countryCode == 'EH') {
$this->countryCode = 'MA';
} elseif ($this->countryCode == 'ZR') {
$this->countryCode = 'CD';
}
return $this->countryCode;
}
public function onKernelResponse(ResponseEvent $event)
{
if ($this->countryCode) {
$cookie = new Cookie('__country', $this->countryCode, time() + 60 * 60 * 24 * 365);
$response = $event->getResponse();
$response->headers->setCookie($cookie);
}
}
}