Skip to content

Commit

Permalink
Simplified localization [SLE-192]
Browse files Browse the repository at this point in the history
  • Loading branch information
samuelgfeller committed Dec 8, 2023
1 parent 8b0b966 commit 2d61d13
Show file tree
Hide file tree
Showing 14 changed files with 171 additions and 128 deletions.
8 changes: 2 additions & 6 deletions config/defaults.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,8 @@

$settings['locale'] = [
'translations_path' => $settings['root_dir'] . '/resources/translations',
// Available languages in this format: ['language' => 'language_COUNTRY'] e.g. ['en' => 'en_US', 'de' => 'de_CH']
// 'available' => [
// 'en' => 'en_US',
// 'de' => 'de_CH',
// 'fr' => 'fr_CH',
// ],
// When adding new available locales, new translated email templates have to be added as well in their
// respective language subdirectory.
'available' => ['en_US', 'de_CH', 'fr_CH'],
'default' => 'en_US',
];
Expand Down
20 changes: 7 additions & 13 deletions src/Application/Middleware/LocaleMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

namespace App\Application\Middleware;

use App\Common\LocaleHelper;
use App\Domain\User\Service\UserFinder;
use App\Infrastructure\Service\LocaleConfigurator;
use Odan\Session\SessionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
Expand All @@ -15,38 +15,32 @@
public function __construct(
private SessionInterface $session,
private UserFinder $userFinder,
private LocaleHelper $localeHelper,
private LocaleConfigurator $localeConfigurator,
) {
}

/**
* Locale middleware set language to default lang, browser lang or from settings.
* Sets language to the user's choice in the database or browser language.
*
* @param ServerRequestInterface $request
* @param RequestHandlerInterface $handler
*
* @return ResponseInterface
*/
public function process(
ServerRequestInterface $request,
RequestHandlerInterface $handler
): ResponseInterface {
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
// Get authenticated user id from session
$loggedInUserId = $this->session->get('user_id');
// If there is an authenticated user, find its language from the database
$userLang = $loggedInUserId ? $this->userFinder->findUserById($loggedInUserId)->language : null;
// Remove the region from the language code en_US -> en
$userLangShort = $userLang ? explode('_', $userLang->value)[0] : null;

// Get browser language. 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
$browserLang = $request->getHeaderLine('Accept-Language');
// Get the first (main) language code with region e.g.: en-GB
$language = explode(',', $browserLang)[0];
// Retrieve only the language part without region e.g.: en
$browserLangShort = explode('-', $language)[0];
$browserLang = explode(',', $browserLang)[0];

// Set the language to the userLang if available and else to the browser language
$actualLocale = $this->localeHelper->setLanguage($userLangShort ?? $browserLangShort);
$actualLocale = $this->localeConfigurator->setLanguage($userLang->value ?? $browserLang);

return $handler->handle($request);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Common/JsImportVersionAdder.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace App\Common;

use App\Domain\Utility\Settings;
use App\Infrastructure\Utility\Settings;
use FilesystemIterator;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
Expand Down
74 changes: 0 additions & 74 deletions src/Common/LocaleHelper.php

This file was deleted.

16 changes: 8 additions & 8 deletions src/Domain/Authentication/Service/LoginMailSender.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

namespace App\Domain\Authentication\Service;

use App\Common\LocaleHelper;
use App\Domain\Service\Infrastructure\Mailer;
use App\Domain\Utility\Settings;
use App\Infrastructure\Service\LocaleConfigurator;
use App\Infrastructure\Service\Mailer;
use App\Infrastructure\Utility\Settings;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
Expand All @@ -18,7 +18,7 @@ class LoginMailSender

public function __construct(
private readonly Mailer $mailer,
private readonly LocaleHelper $localeHelper,
private readonly LocaleConfigurator $localeConfigurator,
Settings $settings
) {
$settings = $settings->get('public')['email'];
Expand All @@ -45,7 +45,7 @@ public function sendInfoToUnverifiedUser(string $email, string $fullName, array
$this->email->subject(__('Login failed because your account is unverified'))
->html(
$this->mailer->getContentFromTemplate(
'authentication/email/' . $this->localeHelper->getLanguageCodeForPath() .
'authentication/email/' . $this->localeConfigurator->getLanguageCodeForPath() .
'login-but-unverified.email.php',
['userFullName' => $fullName, 'queryParams' => $queryParamsWithToken]
)
Expand All @@ -55,7 +55,7 @@ public function sendInfoToUnverifiedUser(string $email, string $fullName, array
}

/**
* When a user tries to log in but his status is suspended.
* When a user tries to log in but their status is suspended.
*
* @param string $email
* @param string $fullName
Expand All @@ -68,7 +68,7 @@ public function sendInfoToSuspendedUser(string $email, string $fullName): void
$this->email->subject(__('Login failed because your account is suspended'))
->html(
$this->mailer->getContentFromTemplate(
'authentication/email/' . $this->localeHelper->getLanguageCodeForPath() .
'authentication/email/' . $this->localeConfigurator->getLanguageCodeForPath() .
'login-but-suspended.email.php',
['userFullName' => $fullName]
)
Expand All @@ -92,7 +92,7 @@ public function sendInfoToLockedUser(string $email, string $fullName, array $que
$this->email->subject(__('Login failed because your account is locked'))
->html(
$this->mailer->getContentFromTemplate(
'authentication/email/' . $this->localeHelper->getLanguageCodeForPath() .
'authentication/email/' . $this->localeConfigurator->getLanguageCodeForPath() .
'login-but-locked.email.php',
['userFullName' => $fullName, 'queryParams' => $queryParamsWithToken]
)
Expand Down
14 changes: 7 additions & 7 deletions src/Domain/Authentication/Service/LoginNonActiveUserHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@

namespace App\Domain\Authentication\Service;

use App\Common\LocaleHelper;
use App\Domain\Authentication\Exception\UnableToLoginStatusNotActiveException;
use App\Domain\Security\Service\SecurityEmailChecker;
use App\Domain\User\Data\UserData;
use App\Domain\User\Enum\UserStatus;
use App\Domain\Utility\Settings;
use App\Infrastructure\Service\LocaleConfigurator;
use App\Infrastructure\Utility\Settings;
use Psr\Log\LoggerInterface;
use Symfony\Component\Mailer\Exception\TransportException;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
Expand All @@ -23,7 +23,7 @@ class LoginNonActiveUserHandler
public function __construct(
private readonly VerificationTokenCreator $verificationTokenCreator,
private readonly LoginMailSender $loginMailer,
private readonly LocaleHelper $localeHelper,
private readonly LocaleConfigurator $localeConfigurator,
private readonly SecurityEmailChecker $securityEmailChecker,
private readonly LoggerInterface $logger,
private readonly AuthenticationLogger $authenticationLogger,
Expand Down Expand Up @@ -73,7 +73,7 @@ public function handleLoginAttemptFromNonActiveUser(

// Change language to the one the user selected in settings (in case it differs from browser lang)
$originalLocale = setlocale(LC_ALL, 0);
$this->localeHelper->setLanguage($dbUser->language->value);
$this->localeConfigurator->setLanguage($dbUser->language->value);

if ($dbUser->status === UserStatus::Unverified) {
// Inform user via email that account is unverified, and he should click on the link in his inbox
Expand All @@ -96,10 +96,10 @@ public function handleLoginAttemptFromNonActiveUser(
throw $unableToLoginException;
}
// Reset locale if sending the mail was successful
$this->localeHelper->setLanguage($originalLocale);
$this->localeConfigurator->setLanguage($originalLocale);
} catch (TransportException $transportException) {
// If exception is thrown reset locale as well. If $unableToLoginException
$this->localeHelper->setLanguage($originalLocale);
$this->localeConfigurator->setLanguage($originalLocale);
// Exception while sending email
throw new UnableToLoginStatusNotActiveException(
'Unable to login at the moment and there was an error when sending an email to you.' .
Expand All @@ -108,7 +108,7 @@ public function handleLoginAttemptFromNonActiveUser(
} // Catch exception to reset locale before throwing it again to be caught in the action
catch (UnableToLoginStatusNotActiveException $unableToLoginStatusNotActiveException) {
// Reset locale
$this->localeHelper->setLanguage($originalLocale);
$this->localeConfigurator->setLanguage($originalLocale);
throw $unableToLoginStatusNotActiveException;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@

namespace App\Domain\Authentication\Service;

use App\Common\LocaleHelper;
use App\Domain\Exception\DomainRecordNotFoundException;
use App\Domain\Security\Service\SecurityEmailChecker;
use App\Domain\Service\Infrastructure\Mailer;
use App\Domain\User\Repository\UserFinderRepository;
use App\Domain\User\Service\UserValidator;
use App\Domain\Utility\Settings;
use App\Domain\Validation\ValidationException;
use App\Infrastructure\Service\LocaleConfigurator;
use App\Infrastructure\Service\Mailer;
use App\Infrastructure\Utility\Settings;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
Expand All @@ -28,7 +28,7 @@ public function __construct(
private readonly VerificationTokenCreator $verificationTokenCreator,
Settings $settings,
private readonly SecurityEmailChecker $securityEmailChecker,
private readonly LocaleHelper $localeHelper,
private readonly LocaleConfigurator $localeConfigurator,
) {
$settings = $settings->get('public')['email'];
// Create email object
Expand Down Expand Up @@ -63,20 +63,20 @@ public function sendPasswordRecoveryEmail(array $userValues, ?string $captcha =

// Change language to one the user chose in settings
$originalLocale = setlocale(LC_ALL, 0);
$this->localeHelper->setLanguage($dbUser->language->value);
$this->localeConfigurator->setLanguage($dbUser->language->value);

// Send verification mail
$this->email->subject(__('Reset password'))->html(
$this->mailer->getContentFromTemplate(
'authentication/email/' . $this->localeHelper->getLanguageCodeForPath() .
'authentication/email/' . $this->localeConfigurator->getLanguageCodeForPath() .
'password-reset.email.php',
['user' => $dbUser, 'queryParams' => $queryParamsWithToken]
)
)->to(new Address($dbUser->email, $dbUser->getFullName()));
// Send email
$this->mailer->send($this->email);
// Reset locale
$this->localeHelper->setLanguage($originalLocale);
$this->localeConfigurator->setLanguage($originalLocale);

// User activity entry is done when user verification token is created
return;
Expand Down
14 changes: 7 additions & 7 deletions src/Domain/Authentication/Service/RegistrationMailSender.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

namespace App\Domain\Authentication\Service;

use App\Common\LocaleHelper;
use App\Domain\Service\Infrastructure\Mailer;
use App\Domain\Utility\Settings;
use App\Infrastructure\Service\LocaleConfigurator;
use App\Infrastructure\Service\Mailer;
use App\Infrastructure\Utility\Settings;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
Expand All @@ -23,7 +23,7 @@ class RegistrationMailSender

public function __construct(
private readonly Mailer $mailer,
private readonly LocaleHelper $localeHelper,
private readonly LocaleConfigurator $localeConfigurator,
Settings $settings
) {
$settings = $settings->get('public')['email'];
Expand All @@ -49,13 +49,13 @@ public function sendRegisterVerificationToken(string $email, string $fullName, s
{
// Change language to one the user is being registered with
$originalLocale = setlocale(LC_ALL, 0);
$this->localeHelper->setLanguage($language);
$this->localeConfigurator->setLanguage($language);

// Send verification mail in the language that was selected for the user
$this->email->subject(__('Account created'))
->html(
$this->mailer->getContentFromTemplate(
'authentication/email/' . $this->localeHelper->getLanguageCodeForPath() .
'authentication/email/' . $this->localeConfigurator->getLanguageCodeForPath() .
'new-account.email.php',
['userFullName' => $fullName, 'queryParams' => $queryParams]
)
Expand All @@ -64,6 +64,6 @@ public function sendRegisterVerificationToken(string $email, string $fullName, s
$this->mailer->send($this->email);

// Reset locale
$this->localeHelper->setLanguage($originalLocale);
$this->localeConfigurator->setLanguage($originalLocale);
}
}
2 changes: 1 addition & 1 deletion src/Domain/Security/Service/EmailRequestFinder.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
namespace App\Domain\Security\Service;

use App\Domain\Security\Repository\EmailLogFinderRepository;
use App\Domain\Utility\Settings;
use App\Infrastructure\Utility\Settings;

class EmailRequestFinder
{
Expand Down
2 changes: 1 addition & 1 deletion src/Domain/Security/Service/LoginRequestFinder.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

use App\Application\Data\UserNetworkSessionData;
use App\Domain\Security\Repository\LoginLogFinderRepository;
use App\Domain\Utility\Settings;
use App\Infrastructure\Utility\Settings;

class LoginRequestFinder
{
Expand Down
2 changes: 1 addition & 1 deletion src/Domain/Security/Service/SecurityCaptchaVerifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

use App\Domain\Security\Enum\SecurityType;
use App\Domain\Security\Exception\SecurityException;
use App\Domain\Utility\Settings;
use App\Infrastructure\Utility\Settings;

class SecurityCaptchaVerifier
{
Expand Down
2 changes: 1 addition & 1 deletion src/Domain/Security/Service/SecurityEmailChecker.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
use App\Domain\Security\Enum\SecurityType;
use App\Domain\Security\Exception\SecurityException;
use App\Domain\Security\Repository\EmailLogFinderRepository;
use App\Domain\Utility\Settings;
use App\Infrastructure\Utility\Settings;

class SecurityEmailChecker
{
Expand Down
Loading

0 comments on commit 2d61d13

Please sign in to comment.