Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
6.67% |
1 / 15 |
|
50.00% |
1 / 2 |
CRAP | |
0.00% |
0 / 1 |
| LanguageController | |
6.67% |
1 / 15 |
|
50.00% |
1 / 2 |
25.33 | |
0.00% |
0 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| switch | |
0.00% |
0 / 14 |
|
0.00% |
0 / 1 |
20 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace App\Web\Controller; |
| 6 | |
| 7 | use App\Domain\Translation\Service\TranslatorInterface; |
| 8 | use App\Domain\Translation\ValueObject\Language; |
| 9 | use App\Web\Middleware\LocaleMiddleware; |
| 10 | use Psr\Http\Message\ResponseFactoryInterface; |
| 11 | use Psr\Http\Message\ResponseInterface; |
| 12 | use Psr\Http\Message\ServerRequestInterface; |
| 13 | |
| 14 | class LanguageController |
| 15 | { |
| 16 | public function __construct( |
| 17 | private TranslatorInterface $translator, |
| 18 | private ResponseFactoryInterface $responseFactory |
| 19 | ) {} |
| 20 | |
| 21 | public function switch(ServerRequestInterface $request): ResponseInterface |
| 22 | { |
| 23 | $queryParams = $request->getQueryParams(); |
| 24 | $langCode = isset($queryParams['lang']) && is_string($queryParams['lang']) ? $queryParams['lang'] : Language::DEFAULT_LOCALE; |
| 25 | |
| 26 | $language = new Language($langCode); |
| 27 | $this->translator->setLocale($language->getCode()); |
| 28 | |
| 29 | $referer = $request->getHeaderLine('Referer'); |
| 30 | $redirectUrl = $referer !== '' ? $referer : '/dashboard'; |
| 31 | |
| 32 | $response = $this->responseFactory->createResponse(302) |
| 33 | ->withHeader('Location', $redirectUrl); |
| 34 | |
| 35 | // Cookie path=/; max-age=1 year |
| 36 | $cookieHeader = sprintf( |
| 37 | '%s=%s; Path=/; Max-Age=31536000; SameSite=Lax', |
| 38 | LocaleMiddleware::COOKIE_NAME, |
| 39 | $language->getCode() |
| 40 | ); |
| 41 | |
| 42 | return $response->withHeader('Set-Cookie', $cookieHeader); |
| 43 | } |
| 44 | } |