Passed
Push — master ( 5e0f86...fc8c86 )
by Tim
02:36
created

LinkLanguageHandler   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 37
rs 10
wmc 4

1 Method

Rating   Name   Duplication   Size   Complexity  
A handle() 0 33 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace LD\LanguageDetection\Handler;
6
7
use LD\LanguageDetection\Event\CheckLanguageDetection;
8
use LD\LanguageDetection\Event\DetectUserLanguages;
9
use LD\LanguageDetection\Event\NegotiateSiteLanguage;
10
use LD\LanguageDetection\Handler\Exception\DisableLanguageDetectionException;
11
use LD\LanguageDetection\Handler\Exception\NoSelectedLanguageException;
12
use LD\LanguageDetection\Handler\Exception\NoUserLanguagesException;
13
use Psr\Http\Message\ResponseInterface;
14
use Psr\Http\Message\ServerRequestInterface;
15
use Psr\Http\Server\RequestHandlerInterface;
16
use TYPO3\CMS\Core\Http\NullResponse;
17
18
/**
19
 * Link handler for handling the language detection, with all 4 core events.
20
 * But the response it not for redirect, it is a NullResponse.
21
 * Please use the detected language uid in the header.
22
 */
23
class LinkLanguageHandler extends AbstractHandler implements RequestHandlerInterface
24
{
25
    public const HEADER_NAME = 'X-LANGUAGE-DETECTION-UID';
26
27
    public function handle(ServerRequestInterface $request): ResponseInterface
28
    {
29
        $site = $this->getSiteFromRequest($request);
30
31
        // @todo check same as:
32
        //$check = new CheckLanguageDetection($site, $this->languageRequest);
33
        //$enableListener = new EnableListener(new SiteConfigurationService());
34
        //$enableListener($check);
35
36
        $check = new CheckLanguageDetection($site, $request);
37
        $this->eventDispatcher->dispatch($check);
38
39
        if (!$check->isLanguageDetectionEnable()) {
40
            throw new DisableLanguageDetectionException();
41
        }
42
43
        $detect = new DetectUserLanguages($site, $request);
44
        $this->eventDispatcher->dispatch($detect);
45
46
        if (empty($detect->getUserLanguages())) {
47
            throw new NoUserLanguagesException();
48
        }
49
50
        $negotiate = new NegotiateSiteLanguage($site, $request, $detect->getUserLanguages());
51
        $this->eventDispatcher->dispatch($negotiate);
52
53
        if (null === $negotiate->getSelectedLanguage()) {
54
            throw new NoSelectedLanguageException();
55
        }
56
57
        $response = new NullResponse();
58
59
        return $response->withAddedHeader(self::HEADER_NAME, (string)$negotiate->getSelectedLanguage()->getLanguageId());
60
    }
61
}
62