Locastic / ApiPlatformTranslationBundle

Translation bundle for ApiPlatform based on Sylius translation
MIT License
85 stars 28 forks source link

Force length 2 for locales #56

Open rsereir opened 2 years ago

rsereir commented 2 years ago

Hello,

Is it possible to force locale have length of 2 chars: instead of fr_FR, i want only fr ?

Rédoine

kevinG73 commented 2 years ago

Hello @rsereir , I don't understand what you mean , where do you want to force 2 chars exactly ?

rsereir commented 2 years ago

@kevinG73 My Accept-Language header is provided by my browser when frontend ( react ) call an api request to my Api Platform API.

This accept language value can be 'fr_FR' but my $locale field have length of 2 chars in my database. So i want to force transformation of fr_FR to fr when ApiPlatformTranslationBundle try to get locale to use

kevinG73 commented 2 years ago

@kevinG73 My Accept-Language header is provided by my browser when frontend ( react ) call an api request to my Api Platform API.

This accept language value can be 'fr_FR' but my $locale field have length of 2 chars in my database. So i want to force transformation of fr_FR to fr when ApiPlatformTranslationBundle try to get locale to use

You can create an EventSubscriber like it :

<?php

namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\HeaderUtils;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class LocaleSubscriber implements EventSubscriberInterface
{

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::REQUEST => [['onKernelRequest', 20]],
        ];
    }

    public function onKernelRequest(RequestEvent $event)
    {
        $request = $event->getRequest();
        $accept_language = $request->headers->get("Accept-Language");
          if (empty($accept_language)) {
            $lang = "fr";
        }else{
             $lang = substr($accept_language, 0, 2);
        }
        $request->setLocale($lang);
        $request->headers->set('Accept-Language', $lang);
         return;
    }
}
rsereir commented 2 years ago

Is there any other way than to rewrite all the language recovery logic already written in the package ApiPlatformTranslationBundle ?

kevinG73 commented 2 years ago

@rsereir yes but in this case then it is not for me to do , I'm not contributor . But add this class simply in any folder inside SRC and it's done