Passed
Push — main ( 656e89...66a587 )
by Tim
06:34 queued 03:15
created

JsonDetectionHandler::handle()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
nc 4
nop 1
dl 0
loc 24
c 1
b 0
f 0
cc 4
rs 9.8333
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Lochmueller\LanguageDetection\Handler;
6
7
use Lochmueller\LanguageDetection\Event\DetectUserLanguagesEvent;
8
use Lochmueller\LanguageDetection\Event\NegotiateSiteLanguageEvent;
9
use Lochmueller\LanguageDetection\Handler\Exception\DisableLanguageDetectionException;
10
use Lochmueller\LanguageDetection\Handler\Exception\NoUserLanguagesException;
11
use Psr\Http\Message\ResponseInterface;
12
use Psr\Http\Message\ServerRequestInterface;
13
use Psr\Http\Server\RequestHandlerInterface;
14
use TYPO3\CMS\Core\Http\JsonResponse;
15
16
/**
17
 * Language detection via "language.json". Do not check if Detection is enabled and
18
 * always output language information.
19
 */
20
class JsonDetectionHandler extends AbstractHandler implements RequestHandlerInterface
21
{
22
    public function handle(ServerRequestInterface $request): ResponseInterface
23
    {
24
        if ($request->getUri()->getPath() !== '/language.json') {
25
            throw new DisableLanguageDetectionException('Wrong URI for JSON detection', 2_346_782);
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_STRING, expecting ',' or ')' on line 25 at column 89
Loading history...
26
        }
27
28
        $site = $this->getSiteFromRequest($request);
29
30
        $detect = new DetectUserLanguagesEvent($site, $request);
31
        $this->eventDispatcher->dispatch($detect);
32
33
        if ($detect->getUserLanguages()->isEmpty()) {
34
            throw new NoUserLanguagesException();
35
        }
36
37
        $negotiate = new NegotiateSiteLanguageEvent($site, $request, $detect->getUserLanguages());
38
        $this->eventDispatcher->dispatch($negotiate);
39
40
        $selectedLanguage = $negotiate->getSelectedLanguage();
41
        if ($selectedLanguage === null) {
42
            return new JsonResponse($site->getDefaultLanguage()->toArray());
43
        }
44
45
        return new JsonResponse($selectedLanguage->toArray());
46
    }
47
}
48