src/Lms/UserInterface/Rest/Controller/LanguageController.php line 36

Open in your IDE?
  1. <?php
  2. namespace CodersLab\Lms\UserInterface\Rest\Controller;
  3. use CodersLab\Lms\SharedKernel\Application\Command\UpdateUserLanguage;
  4. use CodersLab\Lms\SharedKernel\Application\IUserRepository;
  5. use CodersLab\Lms\SharedKernel\Application\Response\LmsApiResponse;
  6. use CodersLab\Lms\SharedKernel\Application\SecurityContext;
  7. use CodersLab\Lms\SharedKernel\Domain\Bus\CommandBus;
  8. use CodersLab\Lms\SharedKernel\Domain\IdentityAccess\UserLanguage;
  9. use OpenApi\Annotations as OA;
  10. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  11. use Symfony\Component\Routing\Annotation\Route;
  12. /**
  13.  * @OA\Tag(name="Language")
  14.  */
  15. final class LanguageController
  16. {
  17.     public function __construct(
  18.         private SessionInterface $session,
  19.         private string $primaryLang,
  20.         private CommandBus $commandBus,
  21.         private SecurityContext $securityContext,
  22.         private IUserRepository $userRepository
  23.     ) {
  24.     }
  25.     /**
  26.      * @Route("/language", name="api_get_lang", methods={"GET"})
  27.      * @OA\Response(
  28.      *     response=200,
  29.      *     description="Get current language"
  30.      * )
  31.      */
  32.     public function getLang(): LmsApiResponse
  33.     {
  34.         return LmsApiResponse::create([
  35.             'lang' => $this->userRepository->getById(
  36.                 (string)$this->securityContext->getLoggedUserId()
  37.             )->getUserLanguage()->getValue() ?? $this->primaryLang,
  38.         ]);
  39.     }
  40.     /**
  41.      * @Route("/language/{lang}", name="api_set_lang", methods={"PUT"})
  42.      * @OA\Parameter(name="lang", in="path", @OA\Schema(type="string"))
  43.      * @OA\Response(
  44.      *     response=200,
  45.      *     description="set current language"
  46.      * )
  47.      */
  48.     public function setLang(string $lang): LmsApiResponse
  49.     {
  50.         if ($this->securityContext->isUserLogged()) {
  51.             $this->commandBus->dispatch(new UpdateUserLanguage(
  52.                 (string)$this->securityContext->getLoggedUserId(),
  53.                 new UserLanguage($lang)
  54.             ));
  55.         }
  56.         $this->session->set('_locale'$lang);
  57.         return LmsApiResponse::create(['lang' => $this->session->get('_locale')]);
  58.     }
  59. }