Passed
Push — main ( 66a587...be085a )
by Tim
12:14
created

GeoPluginDetect   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 20
dl 0
loc 38
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
    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