|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace LD\LanguageDetection\Handler; |
|
6
|
|
|
|
|
7
|
|
|
use LD\LanguageDetection\Event\BuildResponse; |
|
8
|
|
|
use LD\LanguageDetection\Event\CheckLanguageDetection; |
|
9
|
|
|
use LD\LanguageDetection\Event\DetectUserLanguages; |
|
10
|
|
|
use LD\LanguageDetection\Event\NegotiateSiteLanguage; |
|
11
|
|
|
use LD\LanguageDetection\Handler\Exception\DisableLanguageDetectionException; |
|
12
|
|
|
use LD\LanguageDetection\Handler\Exception\NoResponseException; |
|
13
|
|
|
use LD\LanguageDetection\Handler\Exception\NoSelectedLanguageException; |
|
14
|
|
|
use LD\LanguageDetection\Handler\Exception\NoUserLanguagesException; |
|
15
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
16
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
17
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* Core handler for handling the language detection, with all 4 core events. |
|
21
|
|
|
*/ |
|
22
|
|
|
class LanguageDetectionHandler extends AbstractHandler implements RequestHandlerInterface |
|
23
|
|
|
{ |
|
24
|
|
|
public function handle(ServerRequestInterface $request): ResponseInterface |
|
25
|
|
|
{ |
|
26
|
|
|
$site = $this->getSiteFromRequest($request); |
|
27
|
|
|
|
|
28
|
|
|
$check = new CheckLanguageDetection($site, $request); |
|
29
|
|
|
$this->eventDispatcher->dispatch($check); |
|
30
|
|
|
|
|
31
|
|
|
if (!$check->isLanguageDetectionEnable()) { |
|
32
|
|
|
throw new DisableLanguageDetectionException(); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
$detect = new DetectUserLanguages($site, $request); |
|
36
|
|
|
$this->eventDispatcher->dispatch($detect); |
|
37
|
|
|
|
|
38
|
|
|
if (empty($detect->getUserLanguages())) { |
|
39
|
|
|
throw new NoUserLanguagesException(); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
$negotiate = new NegotiateSiteLanguage($site, $request, $detect->getUserLanguages()); |
|
43
|
|
|
$this->eventDispatcher->dispatch($negotiate); |
|
44
|
|
|
|
|
45
|
|
|
if (null === $negotiate->getSelectedLanguage()) { |
|
46
|
|
|
throw new NoSelectedLanguageException(); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
$response = new BuildResponse($site, $request, $negotiate->getSelectedLanguage()); |
|
50
|
|
|
$this->eventDispatcher->dispatch($response); |
|
51
|
|
|
|
|
52
|
|
|
if (null === $response->getResponse()) { |
|
53
|
|
|
throw new NoResponseException(); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
return $response->getResponse(); |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
|