Skip to content

Commit

Permalink
feat: Improved *locale* management by storing _translation into Req…
Browse files Browse the repository at this point in the history
…uest attributes during LocaleSubscriber
  • Loading branch information
ambroisemaupate committed Feb 13, 2024
1 parent 89dd9a3 commit 9e70e04
Show file tree
Hide file tree
Showing 17 changed files with 107 additions and 187 deletions.
22 changes: 0 additions & 22 deletions lib/RoadizCompatBundle/src/Controller/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -303,28 +303,6 @@ public function removeTrailingSlashAction(Request $request): RedirectResponse
return $this->redirect($url, Response::HTTP_MOVED_PERMANENTLY);
}

/**
* Make translation variable with the good localization.
*
* @param Request $request
* @param string|null $_locale
*
* @return TranslationInterface
* @throws NoTranslationAvailableException
*/
protected function bindLocaleFromRoute(Request $request, $_locale = null): TranslationInterface
{
/*
* If you use a static route for Home page
* we need to grab manually language.
*
* Get language from static route
*/
$translation = $this->findTranslationForLocale($_locale);
$request->setLocale($translation->getPreferredLocale());
return $translation;
}

/**
* @param string|null $_locale
*
Expand Down
6 changes: 4 additions & 2 deletions lib/RoadizCompatBundle/src/Controller/FrontendController.php
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,8 @@ public function homeAction(Request $request, $_locale = null)
*
* Get language from static route
*/
$translation = $this->bindLocaleFromRoute($request, $_locale);
/** @var TranslationInterface|null $translation */
$translation = $request->attributes->get('_translation');

/*
* Grab home flagged node
Expand Down Expand Up @@ -304,7 +305,8 @@ protected function extendAssignation()
*/
public function maintenanceAction(Request $request): Response
{
$translation = $this->bindLocaleFromRoute($request, $request->getLocale());
/** @var TranslationInterface|null $translation */
$translation = $request->attributes->get('_translation');
$this->prepareThemeAssignation(null, $translation);

return new Response(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,21 +19,12 @@

final class MaintenanceModeSubscriber implements EventSubscriberInterface
{
private Settings $settings;
private Security $security;
private ThemeResolverInterface $themeResolver;
private ContainerInterface $serviceLocator;

public function __construct(
Settings $settings,
Security $security,
ThemeResolverInterface $themeResolver,
ContainerInterface $serviceLocator
private readonly Settings $settings,
private readonly Security $security,
private readonly ThemeResolverInterface $themeResolver,
private readonly ContainerInterface $serviceLocator
) {
$this->settings = $settings;
$this->security = $security;
$this->themeResolver = $themeResolver;
$this->serviceLocator = $serviceLocator;
}

/**
Expand Down Expand Up @@ -133,15 +124,6 @@ private function getControllerForTheme(Theme $theme, Request $request): Abstract
$request->attributes->set('theme', $controller->getTheme());
}

/*
* Set request locale if _locale param
* is present in Route.
*/
$routeParams = $request->get('_route_params');
if (!empty($routeParams["_locale"])) {
$request->setLocale($routeParams["_locale"]);
}

return $controller;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use RZ\Roadiz\Core\AbstractEntities\PersistableInterface;
use RZ\Roadiz\CoreBundle\Api\DataTransformer\WebResponseDataTransformerInterface;
use RZ\Roadiz\CoreBundle\Api\Model\WebResponseInterface;
use RZ\Roadiz\CoreBundle\Entity\NodesSources;
use RZ\Roadiz\CoreBundle\Entity\Redirection;
use RZ\Roadiz\CoreBundle\NodeType\ApiResourceOperationNameGenerator;
use RZ\Roadiz\CoreBundle\Preview\PreviewResolverInterface;
Expand Down Expand Up @@ -58,6 +59,12 @@ public function __invoke(?Request $request): ?WebResponseInterface
$request->attributes->set('_api_operation_name', $operationName);
$request->attributes->set('_api_resource_class', $resourceClass);
$request->attributes->set('_stateless', true);

if ($resource instanceof NodesSources) {
$request->attributes->set('_translation', $resource->getTranslation());
$request->attributes->set('_locale', $resource->getTranslation()->getPreferredLocale());
}

return $this->webResponseDataTransformer->transform($resource, WebResponseInterface::class);
} catch (ResourceNotFoundException|ResourceClassNotFoundException $exception) {
throw $this->createNotFoundException($exception->getMessage(), $exception);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ abstract protected function getPreviewResolver(): PreviewResolverInterface;
protected function getTranslation(Request $request): TranslationInterface
{
$locale = $request->query->get('_locale');
$requestTranslation = $request->attributes->get('_translation');
if ($requestTranslation instanceof TranslationInterface) {
return $requestTranslation;
}

/** @var TranslationRepository $repository */
$repository = $this->getManagerRegistry()->getRepository(TranslationInterface::class);
if (!\is_string($locale) || $locale === '') {
Expand Down
112 changes: 16 additions & 96 deletions lib/RoadizCoreBundle/src/Controller/CustomFormController.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,12 @@
use League\Flysystem\FilesystemException;
use Limenius\Liform\LiformInterface;
use Psr\Log\LoggerInterface;
use RZ\Roadiz\Core\AbstractEntities\TranslationInterface;
use RZ\Roadiz\CoreBundle\Bag\Settings;
use RZ\Roadiz\CoreBundle\CustomForm\CustomFormHelperFactory;
use RZ\Roadiz\CoreBundle\CustomForm\Message\CustomFormAnswerNotifyMessage;
use RZ\Roadiz\CoreBundle\Entity\CustomForm;
use RZ\Roadiz\CoreBundle\Exception\EntityAlreadyExistsException;
use RZ\Roadiz\CoreBundle\Form\Error\FormErrorSerializerInterface;
use RZ\Roadiz\CoreBundle\Preview\PreviewResolverInterface;
use RZ\Roadiz\CoreBundle\Repository\TranslationRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormInterface;
Expand All @@ -32,47 +29,22 @@
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\RateLimiter\RateLimiterFactory;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Contracts\Translation\LocaleAwareInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

final class CustomFormController extends AbstractController
{
private Settings $settingsBag;
private LoggerInterface $logger;
private TranslatorInterface $translator;
private CustomFormHelperFactory $customFormHelperFactory;
private LiformInterface $liform;
private SerializerInterface $serializer;
private FormErrorSerializerInterface $formErrorSerializer;
private ManagerRegistry $registry;
private RateLimiterFactory $customFormLimiter;
private PreviewResolverInterface $previewResolver;
private MessageBusInterface $messageBus;

public function __construct(
Settings $settingsBag,
LoggerInterface $logger,
TranslatorInterface $translator,
CustomFormHelperFactory $customFormHelperFactory,
LiformInterface $liform,
SerializerInterface $serializer,
FormErrorSerializerInterface $formErrorSerializer,
ManagerRegistry $registry,
RateLimiterFactory $customFormLimiter,
PreviewResolverInterface $previewResolver,
MessageBusInterface $messageBus,
private readonly Settings $settingsBag,
private readonly LoggerInterface $logger,
private readonly TranslatorInterface $translator,
private readonly CustomFormHelperFactory $customFormHelperFactory,
private readonly LiformInterface $liform,
private readonly SerializerInterface $serializer,
private readonly FormErrorSerializerInterface $formErrorSerializer,
private readonly ManagerRegistry $registry,
private readonly RateLimiterFactory $customFormLimiter,
private readonly MessageBusInterface $messageBus,
) {
$this->settingsBag = $settingsBag;
$this->logger = $logger;
$this->translator = $translator;
$this->customFormHelperFactory = $customFormHelperFactory;
$this->liform = $liform;
$this->serializer = $serializer;
$this->formErrorSerializer = $formErrorSerializer;
$this->registry = $registry;
$this->customFormLimiter = $customFormLimiter;
$this->previewResolver = $previewResolver;
$this->messageBus = $messageBus;
}

protected function validateCustomForm(?CustomForm $customForm): void
Expand All @@ -85,38 +57,6 @@ protected function validateCustomForm(?CustomForm $customForm): void
}
}

protected function getTranslationFromRequest(?Request $request): TranslationInterface
{
$locale = null;

if (null !== $request) {
$locale = $request->query->get('_locale');

/*
* If no _locale query param is defined check Accept-Language header
*/
if (null === $locale) {
$locale = $request->getPreferredLanguage($this->getTranslationRepository()->getAllLocales());
}
}
/*
* Then fallback to default CMS locale
*/
if (null === $locale) {
$translation = $this->getTranslationRepository()->findDefault();
} elseif ($this->previewResolver->isPreview()) {
$translation = $this->getTranslationRepository()
->findOneByLocaleOrOverrideLocale((string) $locale);
} else {
$translation = $this->getTranslationRepository()
->findOneAvailableByLocaleOrOverrideLocale((string) $locale);
}
if (null === $translation) {
throw new NotFoundHttpException('No translation for locale ' . $locale);
}
return $translation;
}

/**
* @param Request $request
* @param int $id
Expand All @@ -129,11 +69,6 @@ public function definitionAction(Request $request, int $id): JsonResponse
$this->validateCustomForm($customForm);

$helper = $this->customFormHelperFactory->createHelper($customForm);
$translation = $this->getTranslationFromRequest($request);
$request->setLocale($translation->getPreferredLocale());
if ($this->translator instanceof LocaleAwareInterface) {
$this->translator->setLocale($translation->getPreferredLocale());
}
$schema = json_encode($this->liform->transform($helper->getForm($request, false, false)));

return new JsonResponse(
Expand Down Expand Up @@ -169,12 +104,6 @@ public function postAction(Request $request, int $id): Response
$customForm = $this->registry->getRepository(CustomForm::class)->find($id);
$this->validateCustomForm($customForm);

$translation = $this->getTranslationFromRequest($request);
$request->setLocale($translation->getPreferredLocale());
if ($this->translator instanceof LocaleAwareInterface) {
$this->translator->setLocale($translation->getPreferredLocale());
}

$mixed = $this->prepareAndHandleCustomFormAssignation(
$request,
$customForm,
Expand Down Expand Up @@ -322,10 +251,13 @@ public function prepareAndHandleCustomFormAssignation(
['%name%' => $customFormsEntity->getDisplayName()]
);

$session = $request->getSession();
if ($session instanceof Session) {
$session->getFlashBag()->add('confirm', $msg);
if (!$request->attributes->getBoolean('_stateless') && $request->hasPreviousSession()) {
$session = $request->getSession();
if ($session instanceof Session) {
$session->getFlashBag()->add('confirm', $msg);
}
}

$this->logger->info($msg);

return $response;
Expand All @@ -338,16 +270,4 @@ public function prepareAndHandleCustomFormAssignation(
$assignation['formObject'] = $form;
return $assignation;
}

protected function getTranslationRepository(): TranslationRepository
{
$repository = $this->registry->getRepository(TranslationInterface::class);
if (!$repository instanceof TranslationRepository) {
throw new \RuntimeException(
'Translation repository must be instance of ' .
TranslationRepository::class
);
}
return $repository;
}
}
Loading

0 comments on commit 9e70e04

Please sign in to comment.