dachcom-digital / pimcore-i18n

Pimcore - i18n Manager
Other
28 stars 18 forks source link

Wrong locale in static routes #104

Closed pascalmoser closed 1 year ago

pascalmoser commented 2 years ago
Q A
Bug report? yes
Feature request? no
BC Break report? no
RFC? no

Pimcore Translator has a wrong locale in static routes when country context is missing in language attribute. Eg. Document locale: de_CH, static route: www.project.ch/de/my-static-route/object-xy

Fix in project:

<?php

namespace App\EventListener;

use I18nBundle\Helper\RequestValidatorHelper;
use I18nBundle\Resolver\PimcoreDocumentResolverInterface;
use Pimcore\Model\Document;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class StaticRouteLocaleListener implements EventSubscriberInterface
{
    protected PimcoreDocumentResolverInterface $pimcoreDocumentResolver;
    protected RequestValidatorHelper $requestValidatorHelper;

    public function __construct(
        PimcoreDocumentResolverInterface $pimcoreDocumentResolver,
        RequestValidatorHelper $requestValidatorHelper)
    {
        $this->pimcoreDocumentResolver = $pimcoreDocumentResolver;
        $this->requestValidatorHelper = $requestValidatorHelper;
    }

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::REQUEST   => [
                ['onKernelRequestLocale', 17],      // before symfony LocaleListener
            ]
        ];
    }

    public function onKernelRequestLocale(RequestEvent $event)
    {
        if ($event->isMainRequest() === false) {
            return;
        }

        $request = $event->getRequest();
        $document = $this->pimcoreDocumentResolver->getDocument($request);

        if (!$document instanceof Document) {
            return;
        }

        if (!$this->requestValidatorHelper->isValidForRedirect($request)) {
            return;
        }

        $documentLocale = $document->getProperty('language');
        $requestSource = $request->attributes->get('pimcore_request_source');

        if ($requestSource === 'staticroute' && !empty($documentLocale) && $request->attributes->get('_locale') !== $documentLocale) {
            $request->attributes->set('_locale', $documentLocale);
        }
    }
}