samuelgfeller /
slim-example-project
| 1 | <?php |
||
| 2 | |||
| 3 | namespace App\Application\Middleware; |
||
| 4 | |||
| 5 | use App\Infrastructure\Locale\LocaleConfigurator; |
||
| 6 | use App\Module\User\Find\Service\UserFinder; |
||
| 7 | use Odan\Session\SessionInterface; |
||
| 8 | use Psr\Http\Message\ResponseInterface; |
||
| 9 | use Psr\Http\Message\ServerRequestInterface; |
||
| 10 | use Psr\Http\Server\MiddlewareInterface; |
||
| 11 | use Psr\Http\Server\RequestHandlerInterface; |
||
| 12 | |||
| 13 | final readonly class LocaleMiddleware implements MiddlewareInterface |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 14 | { |
||
| 15 | 203 | public function __construct( |
|
| 16 | private SessionInterface $session, |
||
| 17 | private UserFinder $userFinder, |
||
| 18 | private LocaleConfigurator $localeConfigurator, |
||
| 19 | ) { |
||
| 20 | 203 | } |
|
| 21 | |||
| 22 | /** |
||
| 23 | * Sets language to the user's choice in the database or browser language. |
||
| 24 | * |
||
| 25 | * @param ServerRequestInterface $request |
||
| 26 | * @param RequestHandlerInterface $handler |
||
| 27 | * |
||
| 28 | * @return ResponseInterface |
||
| 29 | */ |
||
| 30 | 203 | public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
|
| 31 | { |
||
| 32 | // Get authenticated user id from session |
||
| 33 | 203 | $loggedInUserId = $this->session->get('user_id'); |
|
| 34 | // If there is an authenticated user, find their language in the database |
||
| 35 | 203 | $locale = $loggedInUserId ? $this->userFinder->findUserById($loggedInUserId)->language->value : null; |
|
| 36 | // Get browser language if no user language is set |
||
| 37 | 203 | if (!$locale) { |
|
| 38 | // Result is something like: en-GB,en;q=0.9,de;q=0.8,de-DE;q=0.7,en-US;q=0.6,pt;q=0.5,fr;q=0.4 |
||
| 39 | 55 | $browserLang = $request->getHeaderLine('Accept-Language'); |
|
| 40 | // Get the first (main) language code with region e.g.: en-GB |
||
| 41 | 55 | $locale = explode(',', $browserLang)[0]; |
|
| 42 | } |
||
| 43 | // Set the language to the userLang if available and else to the browser language |
||
| 44 | 203 | $this->localeConfigurator->setLanguage($locale); |
|
| 45 | |||
| 46 | 203 | return $handler->handle($request); |
|
| 47 | } |
||
| 48 | } |
||
| 49 |