1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Lochmueller\LanguageDetection\Detect; |
6
|
|
|
|
7
|
|
|
use Lochmueller\LanguageDetection\Domain\Model\Dto\LocaleValueObject; |
8
|
|
|
use Lochmueller\LanguageDetection\Event\DetectUserLanguagesEvent; |
9
|
|
|
use Lochmueller\LanguageDetection\Service\IpLocation; |
10
|
|
|
use Lochmueller\LanguageDetection\Service\LanguageService; |
11
|
|
|
use Lochmueller\LanguageDetection\Service\LocaleCollectionSortService; |
12
|
|
|
use Lochmueller\LanguageDetection\Service\SiteConfigurationService; |
13
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Location Service. |
17
|
|
|
* |
18
|
|
|
* Get the Location based on the IP. |
19
|
|
|
* Use the geoplugin.net API. |
20
|
|
|
*/ |
21
|
|
|
class GeoPluginDetect |
22
|
|
|
{ |
23
|
|
|
protected IpLocation $ipLocation; |
24
|
|
|
protected LanguageService $languageService; |
25
|
|
|
protected SiteConfigurationService $siteConfigurationService; |
26
|
|
|
protected LocaleCollectionSortService $localeCollectionSortService; |
27
|
|
|
|
28
|
|
|
public function __construct(IpLocation $ipLocation, LanguageService $languageService, SiteConfigurationService $siteConfigurationService, LocaleCollectionSortService $localeCollectionSortService) |
29
|
|
|
{ |
30
|
|
|
$this->ipLocation = $ipLocation; |
31
|
|
|
$this->languageService = $languageService; |
32
|
|
|
$this->siteConfigurationService = $siteConfigurationService; |
33
|
|
|
$this->localeCollectionSortService = $localeCollectionSortService; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public function __invoke(DetectUserLanguagesEvent $event): void |
37
|
|
|
{ |
38
|
|
|
$addIp = $this->siteConfigurationService->getConfiguration($event->getSite())->getAddIpLocationToBrowserLanguage(); |
39
|
|
|
if (!\in_array($addIp, [LocaleCollectionSortService::SORT_BEFORE, LocaleCollectionSortService::SORT_AFTER, LocaleCollectionSortService::SORT_REPLACE], true)) { |
40
|
|
|
return; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
$locale = $this->getLocale($event->getRequest()); |
44
|
|
|
if ($locale === null) { |
45
|
|
|
return; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
$event->setUserLanguages($this->localeCollectionSortService->addLocaleByMode($event->getUserLanguages(), new LocaleValueObject($locale), $addIp)); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public function getLocale(ServerRequestInterface $request): ?string |
52
|
|
|
{ |
53
|
|
|
$countryCode = $this->ipLocation->getCountryCode($request->getServerParams()['REMOTE_ADDR'] ?? ''); |
54
|
|
|
if ($countryCode === null) { |
55
|
|
|
return null; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
return $this->languageService->getLanguageByCountry($countryCode) . '_' . $countryCode; |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|