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

GeoPluginDetect::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 4
dl 0
loc 6
rs 10
c 0
b 0
f 0
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