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
|
|
|
public function __construct( |
24
|
|
|
protected IpLocation $ipLocation, |
25
|
|
|
protected LanguageService $languageService, |
26
|
|
|
protected SiteConfigurationService $siteConfigurationService, |
27
|
|
|
protected LocaleCollectionSortService $localeCollectionSortService |
28
|
|
|
) {} |
29
|
|
|
|
30
|
|
|
public function __invoke(DetectUserLanguagesEvent $event): void |
31
|
|
|
{ |
32
|
|
|
$addIp = $this->siteConfigurationService->getConfiguration($event->getSite())->getAddIpLocationToBrowserLanguage(); |
33
|
|
|
if (!\in_array($addIp, [LocaleCollectionSortService::SORT_BEFORE, LocaleCollectionSortService::SORT_AFTER, LocaleCollectionSortService::SORT_REPLACE], true)) { |
34
|
|
|
return; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
$locale = $this->getLocale($event->getRequest()); |
38
|
|
|
if ($locale === null) { |
39
|
|
|
return; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
$event->setUserLanguages($this->localeCollectionSortService->addLocaleByMode($event->getUserLanguages(), new LocaleValueObject($locale), $addIp)); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
public function getLocale(ServerRequestInterface $request): ?string |
46
|
|
|
{ |
47
|
|
|
$countryCode = $this->ipLocation->getCountryCode($request->getServerParams()['REMOTE_ADDR'] ?? ''); |
48
|
|
|
if ($countryCode === null) { |
49
|
|
|
return null; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
return $this->languageService->getLanguageByCountry($countryCode) . '_' . $countryCode; |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|