GeoPluginDetect   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 32
rs 10
c 0
b 0
f 0
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A __invoke() 0 13 3
A getLocale() 0 8 2
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