<?php declare(strict_types=1);
namespace Acris\ShopSwitch\Components\GeoTargeting;
use Acris\ShopSwitch\AcrisShopSwitchCS as AcrisShopSwitch;
use Acris\ShopSwitch\Components\Simulation\SimulationService;
use GeoIp2\Database\Reader as Reader;
//require_once '../../Resources/GeoIp2/vendor/autoload.php';
class Ip2CountryService
{
/**
* @var AcrisShopSwitch
*/
private $acrisShopSwitchPlugin;
private SimulationService $simulationService;
public function __construct(AcrisShopSwitch $acrisShopSwitchPlugin, SimulationService $simulationService)
{
$this->acrisShopSwitchPlugin = $acrisShopSwitchPlugin;
include_once($this->acrisShopSwitchPlugin->getPath() . '/Resources/GeoIp2/vendor/autoload.php');
$this->simulationService = $simulationService;
}
/**
* @param string $ip ip v4 address
* @return string with country data
* @throws \MaxMind\Db\Reader\InvalidDatabaseException
*/
public function ip2country($ip, string $salesChannelId): ?string
{
$simulatedIsoFromConfig = $this->simulationService->getSimulatedCountryIsoFromConfig($ip, $salesChannelId);
if(empty($simulatedIsoFromConfig) === false) {
return $simulatedIsoFromConfig;
}
$database = $this->acrisShopSwitchPlugin->getPath() . '/Resources/GeoIp2/GeoLite2-Country.mmdb';
if(file_exists($database) === false) {
return null;
}
$reader = new Reader($database);
try {
$record = $reader->country($ip);
$iso = $record->country->isoCode;
} catch (\Exception $e) {
$iso = "";
}
return $iso;
}
}