Skip to content

Instantly share code, notes, and snippets.

@Ellrion
Last active November 10, 2017 15:33
Show Gist options
  • Save Ellrion/c02c196b30c894c19f27 to your computer and use it in GitHub Desktop.
Save Ellrion/c02c196b30c894c19f27 to your computer and use it in GitHub Desktop.
laravel localosation old (<=5.0)
<?php
//...
Route::filter('l10n', function () {
if (is_null(App::make('langDetector')->getLangSlug())) {
return Redirect::to(App::make('langDetector')->getLangRequestUri());
}
App::make('langDetector')->setLang();
});
<?php
class LanguageDetector
{
private $languages = [];
public function __construct($enabledLanguages)
{
$this->languages = (array)$enabledLanguages;
}
public function getLangSlug()
{
return in_array(Request::segment(1), $this->languages, true) ? Request::segment(1) : null;
}
public function setLang()
{
$lng = $this->getLangSlug();
if (!is_null($lng)) {
Session::put('locale', $lng);
}
if ( Session::has('locale') ) {
App::setLocale(Session::get('locale'));
}
}
public function getPureUri($uri)
{
return preg_replace('~^/(?:'.implode('|', $this->languages).')/?(.*)$~', '/$1', $uri);
}
public function getLangUri($uri, $lang = null)
{
$uri = (is_null($lang) || !in_array($lang, $this->languages, true) ? App::getLocale() : $lang)
.'/'.ltrim($this->getPureUri($uri), '/');
return '/'.trim($uri, '/');
}
public function getPureRequestUri()
{
return $this->getPureUri(Request::getRequestUri());
}
public function getLangRequestUri($lang = null)
{
return $this->getLangUri(Request::getRequestUri(), $lang);
}
}
<?php
use Illuminate\Support\ServiceProvider;
class LanguageDetectorServiceProvider
extends ServiceProvider
{
public function register()
{
$this->app->singleton('langDetector', function($app) {
return new LanguageDetector($app['config']->get('app.enabled_languages'));
});
}
}
<?php
//...
Route::group(['prefix' => App::make('langDetector')->getLangSlug(), 'before' => 'l10n'], function () {
//...
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment