Welcome Guest, Not a member yet? Register   Sign In
{locale} placeholder in routes
#2

You are right, it doesn't make a lot of sense how unsupported locales are handled by the framework. Instead of a custom router, I made a filter :

PHP Code:
<?php
namespace App\Filters;

use 
CodeIgniter\HTTP\RequestInterface;
use 
CodeIgniter\HTTP\ResponseInterface;
use 
CodeIgniter\Filters\FilterInterface;

class 
Localize implements FilterInterface
{
    public function before(RequestInterface $request$arguments null)
    {
        log_message('debug'"FilterLocalize --- start ---");
        $uri = &$request->uri;
        $segments array_filter($uri->getSegments());
        $nbSegments count($segments);
        log_message('debug'"FilterLocalize - {$nbSegments} segments = " print_r($segmentstrue));

        // Keep only the first 2 letters (en-UK => en)
        $userLocale strtolower(substr($request->getLocale(), 02));
        log_message('debug'"FilterLocalize - Visitor's locale $userLocale");

        // If the user's language is not a supported language, take the default language
        $locale in_array($userLocale$request->config->supportedLocales) ? $userLocale $request->config->defaultLocale;
        log_message('debug'"FilterLocalize - Selected locale $locale");

        // If we request /, redirect to /{locale}
        if ($nbSegments == 0)
        {
            log_message('debug'"FilterLocalize - Redirect / to /{$locale}");
            log_message('debug'"FilterLocalize --- end ---");
            return redirect()->to("/{$locale}");
        }

        log_message('debug'"FilterLocalize - segments[0] = " $segments[0]);
        $locale $segments[0];

        // If the first segment of the URI is not a valid locale, trigger a 404 error
        if ( ! in_array($locale$request->config->supportedLocales))
        {
            log_message('debug'"FilterLocalize - ERROR Invalid locale '{$locale}'");
            log_message('debug'"FilterLocalize --- end ---");
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        log_message('debug'"FilterLocalize - Valid locale '$locale'");
        log_message('debug'"FilterLocalize --- end ---");
    }

    public function after(RequestInterface $requestResponseInterface $response$arguments null)
    {
        // Do something here
    }


CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply


Messages In This Thread
{locale} placeholder in routes - by webdeveloper - 06-08-2022, 06:23 AM
RE: {locale} placeholder in routes - by includebeer - 06-08-2022, 03:10 PM
RE: {locale} placeholder in routes - by InsiteFX - 06-09-2022, 11:57 PM
RE: {locale} placeholder in routes - by kenjis - 06-10-2022, 06:05 PM



Theme © iAndrew 2016 - Forum software by © MyBB