Skip to content

Commit 952d268

Browse files
author
Marc Cámara
committed
Added Session and Cookie Middlewares
1 parent 2f43106 commit 952d268

File tree

7 files changed

+107
-130
lines changed

7 files changed

+107
-130
lines changed

CHANGELOG.md

+4
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
### 1.0.7
2+
- Added Session and Cookie Middleware
3+
- Deleted useSessionLocale and useCookieLocale from config file
4+
15
### 1.0
26
- Laravel 5 supported
37
- Added Middleware

README.md

+10-5
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ Easy i18n localization for Laravel, an useful tool to combine with Laravel local
1313
- <a href="#laravel">Laravel</a>
1414
- <a href="#usage">Usage</a>
1515
- <a href="#middleware">Middleware</a>
16+
- <a href="#sessions">Sessions</a>
1617
- <a href="#helpers">Helpers</a>
1718
- <a href="#translated-routes">Translated Routes</a>
1819
- <a href="#config">Config</a>
@@ -100,7 +101,7 @@ Once this route group is added to the routes file, a user can access all locales
100101

101102
If the locale is not present in the url or it is not defined in `supportedLocales`, the system will use the application default locale or the user's browser default locale (if defined in config file).
102103

103-
Once the locale is defined, the locale variable will be stored in a session, so it is not necessary to write the /lang/ section in the url after defining it once, using the last known locale for the user. If the user accesses to a different locale this session value would be changed, translating any other page he visits with the last chosen locale.
104+
Once the locale is defined, the locale variable will be stored in a session (if the middleware is enabled), so it is not necessary to write the /lang/ section in the url after defining it once, using the last known locale for the user. If the user accesses to a different locale this session value would be changed, translating any other page he visits with the last chosen locale.
104105

105106
Template files and all locale files should follow the [Lang class](http://laravel.com/docs/5.0/localization).
106107

@@ -165,6 +166,14 @@ If you want to hide the default locale but always show other locales in the url,
165166

166167
**IMPORTANT** - When `hideDefaultLocaleInURL` is set to true, the unlocalized root is treated as the applications default locale `app.locale`. Because of this language negotiation using the Accept-Language header will **NEVER** occur when `hideDefaultLocaleInURL` is true.
167168

169+
### Sessions
170+
171+
In version 1.0.7 a new middleware to control session storage has been added. I have created it because Laravel 5 changed the order for calls and you cannot access to the session from a function called from 'prefix'.
172+
173+
To use it just add `Mcamara\LaravelLocalization\Middleware\LocaleSessionRedirect` to the Middleware list, it will automatically store and redirect users to the locale stored in the session.
174+
175+
Just a reminder, old config values like `useSessionLocale` and `useCookieLocale` will be ignored.
176+
168177
## Helpers
169178

170179
This package comes with some useful functions, like:
@@ -490,10 +499,6 @@ For example, editing the default config service provider that Laravel loads when
490499

491500
'laravellocalization.useAcceptLanguageHeader' => true,
492501

493-
'laravellocalization.useSessionLocale' => true,
494-
495-
'laravellocalization.useCookieLocale' => true,
496-
497502
'laravellocalization.hideDefaultLocaleInURL' => true
498503
]);
499504
}

composer.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"keywords": ["localization", "laravel", "php"],
55
"homepage": "https://github.com/mcamara/laravel-localization",
66
"license": "MIT",
7-
"version": "1.0.6",
7+
"version": "1.0.7",
88
"authors": [
99
{
1010
"name": "Marc Cámara",

src/Mcamara/LaravelLocalization/LaravelLocalization.php

+13-109
Original file line numberDiff line numberDiff line change
@@ -96,13 +96,6 @@ class LaravelLocalization {
9696
*/
9797
protected $routeName;
9898

99-
/**
100-
* Name of the locale variable for the session and cookie storages
101-
*
102-
* @var string
103-
*/
104-
protected $cookieSessionName = 'locale';
105-
10699
/**
107100
* Creates new instance.
108101
* @throws UnsupportedLocaleException
@@ -111,10 +104,10 @@ public function __construct()
111104
{
112105
$this->app = app();
113106

114-
$this->configRepository = $this->app['config'];
115-
$this->view = $this->app['view'];
116-
$this->translator = $this->app['translator'];
117-
$this->router = $this->app['router'];
107+
$this->configRepository = $this->app[ 'config' ];
108+
$this->view = $this->app[ 'view' ];
109+
$this->translator = $this->app[ 'translator' ];
110+
$this->router = $this->app[ 'router' ];
118111
$this->request = $this->app[ 'request' ];
119112

120113
// set default locale
@@ -150,7 +143,7 @@ public function setLocale( $locale = null )
150143
{
151144
// if the first segment/locale passed is not valid
152145
// the system would ask which locale have to take
153-
// it could be taken by session, browser or app default
146+
// it could be taken by the browser
154147
// depending on your configuration
155148

156149
$locale = null;
@@ -162,7 +155,7 @@ public function setLocale( $locale = null )
162155
$this->currentLocale = $this->defaultLocale;
163156
}
164157
// but if hideDefaultLocaleInURL is false, we have
165-
// to retrieve it from the session/cookie/browser...
158+
// to retrieve it from the browser...
166159
else
167160
{
168161
$this->currentLocale = $this->getCurrentLocale();
@@ -171,10 +164,6 @@ public function setLocale( $locale = null )
171164

172165
$this->app->setLocale($this->currentLocale);
173166

174-
$this->storeSession($this->currentLocale);
175-
176-
$this->storeCookie($this->currentLocale);
177-
178167
return $locale;
179168
}
180169

@@ -340,7 +329,6 @@ public function getURLFromRouteNameTranslated( $locale, $transKeyName, $attribut
340329
{
341330
$route = '/' . $locale;
342331
}
343-
344332
if ( is_string($locale) && $this->translator->has($transKeyName, $locale) )
345333
{
346334
$translation = $this->translator->trans($transKeyName, [ ], "", $locale);
@@ -479,19 +467,6 @@ public function getCurrentLocale()
479467
return $this->currentLocale;
480468
}
481469

482-
// get session language...
483-
if ( $locale = $this->getSessionLocale() )
484-
{
485-
return $locale;
486-
}
487-
488-
// or get cookie language...
489-
if ( $locale = $this->getCookieLocale() )
490-
{
491-
return $locale;
492-
}
493-
494-
// or get browser language...
495470
if ( $this->useAcceptLanguageHeader() )
496471
{
497472
$negotiator = new LanguageNegotiator($this->defaultLocale, $this->getSupportedLocales(), $this->request);
@@ -514,60 +489,6 @@ public function getSupportedLanguagesKeys()
514489
}
515490

516491

517-
/**
518-
* Returns the locale stored on the session (if available)
519-
*
520-
* @return string|false Locale stored in session - False if it doesn't exist
521-
*/
522-
protected function getSessionLocale()
523-
{
524-
if ( $this->useSessionLocale() && app('session')->has($this->cookieSessionName) )
525-
{
526-
return session($this->cookieSessionName);
527-
}
528-
529-
return false;
530-
}
531-
532-
/**
533-
* Store the locale on a session variable
534-
* @param $locale string Locale to save on session variable
535-
*/
536-
protected function storeSession( $locale )
537-
{
538-
if ( $this->useSessionLocale() )
539-
{
540-
session([ $this->cookieSessionName => $locale ]);
541-
}
542-
}
543-
544-
/**
545-
* Returns the locale stored on the cookies (if available)
546-
*
547-
* @return string|false Locale stored in cookies - False if it doesn't exist
548-
*/
549-
protected function getCookieLocale()
550-
{
551-
if ( $this->useCookieLocale() )
552-
{
553-
return cookie($this->cookieSessionName)->getValue();
554-
}
555-
556-
return false;
557-
}
558-
559-
/**
560-
* Store the locale on a cookie variable
561-
* @param $locale String Locale to store on Cookie variable
562-
*/
563-
protected function storeCookie( $locale )
564-
{
565-
if ( $this->useCookieLocale() )
566-
{
567-
cookie($this->cookieSessionName, $locale);
568-
}
569-
}
570-
571492
/**
572493
* Check if Locale exists on the supported locales array
573494
*
@@ -639,6 +560,7 @@ public function transRoute( $routeName )
639560
{
640561
$this->translatedRoutes[ ] = $routeName;
641562
}
563+
642564
return $this->translator->trans($routeName);
643565
}
644566

@@ -663,11 +585,12 @@ public function getRouteNameFromAPath( $path )
663585

664586
foreach ( $this->translatedRoutes as $route )
665587
{
666-
if ( $this->substituteAttributesInRoute( $attributes, $this->translator->trans($route)) === $path )
588+
if ( $this->substituteAttributesInRoute($attributes, $this->translator->trans($route)) === $path )
667589
{
668590
return $route;
669591
}
670592
}
593+
671594
return false;
672595
}
673596

@@ -751,25 +674,6 @@ public function getConfigRepository()
751674
return $this->configRepository;
752675
}
753676

754-
/**
755-
* Returns the translation key for a given path
756-
*
757-
* @return boolean Returns value of useSessionLocale in config.
758-
*/
759-
protected function useSessionLocale()
760-
{
761-
return $this->configRepository->get('laravellocalization.useSessionLocale');
762-
}
763-
764-
/**
765-
* Returns the translation key for a given path
766-
*
767-
* @return boolean Returns value of useCookieLocale in config.
768-
*/
769-
protected function useCookieLocale()
770-
{
771-
return $this->configRepository->get('laravellocalization.useCookieLocale');
772-
}
773677

774678
/**
775679
* Returns the translation key for a given path
@@ -799,12 +703,14 @@ public function hideDefaultLocaleInURL()
799703
*/
800704
public function createUrlFromUri( $uri )
801705
{
706+
$uri = ltrim($uri, "/");
707+
802708
if ( empty( $this->baseUrl ) )
803709
{
804710
return app('url')->to($uri);
805711
}
806712

807-
return $this->baseUrl . ltrim($uri, "/");
713+
return $this->baseUrl . $uri;
808714
}
809715

810716
/**
@@ -904,8 +810,7 @@ protected function extractAttributes( $url = false )
904810
}
905811
}
906812

907-
}
908-
else
813+
} else
909814
{
910815
if ( !$this->router->current() )
911816
{
@@ -927,7 +832,6 @@ protected function extractAttributes( $url = false )
927832
}
928833

929834

930-
931835
return $attributes;
932836
}
933837

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php namespace Mcamara\LaravelLocalization\Middleware;
2+
3+
use Illuminate\Contracts\Routing\Middleware;
4+
use Illuminate\Http\RedirectResponse;
5+
use Closure;
6+
7+
8+
class LocaleCookieRedirect implements Middleware {
9+
10+
/**
11+
* Handle an incoming request.
12+
*
13+
* @param \Illuminate\Http\Request $request
14+
* @param \Closure $next
15+
* @return mixed
16+
*/
17+
public function handle( $request, Closure $next )
18+
{
19+
$params = explode('/', $request->path());
20+
21+
if ( count($params) > 0 && $locale = app('laravellocalization')->checkLocaleInSupportedLocales($params[ 0 ]) )
22+
{
23+
cookie('locale', $params[ 0 ]);
24+
25+
return $next($request);
26+
}
27+
28+
$locale = $request->cookie('locale', false);
29+
30+
if ( $locale && !( app('laravellocalization')->getDefaultLocale() === $locale && app('laravellocalization')->hideDefaultLocaleInURL() ) )
31+
{
32+
app('session')->reflash();
33+
$redirection = app('laravellocalization')->getLocalizedURL($locale);
34+
35+
return new RedirectResponse($redirection, 302, [ 'Vary', 'Accept-Language' ]);
36+
}
37+
38+
return $next($request);
39+
}
40+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<?php namespace Mcamara\LaravelLocalization\Middleware;
2+
3+
use Illuminate\Contracts\Routing\Middleware;
4+
use Illuminate\Http\RedirectResponse;
5+
use Closure;
6+
7+
class LocaleSessionRedirect implements Middleware {
8+
9+
/**
10+
* Handle an incoming request.
11+
*
12+
* @param \Illuminate\Http\Request $request
13+
* @param \Closure $next
14+
* @return mixed
15+
*/
16+
public function handle( $request, Closure $next )
17+
{
18+
$params = explode('/', $request->path());
19+
20+
if ( count($params) > 0 && $locale = app('laravellocalization')->checkLocaleInSupportedLocales($params[ 0 ]) )
21+
{
22+
session([ 'locale' => $params[ 0 ] ]);
23+
24+
return $next($request);
25+
}
26+
27+
$locale = session('locale', false);
28+
29+
if ( $locale && !( app('laravellocalization')->getDefaultLocale() === $locale && app('laravellocalization')->hideDefaultLocaleInURL() ) )
30+
{
31+
app('session')->reflash();
32+
$redirection = app('laravellocalization')->getLocalizedURL($locale);
33+
34+
return new RedirectResponse($redirection, 302, [ 'Vary', 'Accept-Language' ]);
35+
}
36+
37+
return $next($request);
38+
}
39+
}

src/config/config.php

-15
Original file line numberDiff line numberDiff line change
@@ -301,21 +301,6 @@
301301
// If false, system will take app.php locale attribute
302302
'useAcceptLanguageHeader' => true,
303303

304-
// Should application use the locale stored in a session
305-
// if the locale is not defined in the url?
306-
// If false and locale not defined in the url, the system will
307-
// take the default locale (defined in config/app.php) or
308-
// the browser preferred language (if useAcceptLanguageHeader is true) or
309-
// the cookie locale (if useCookieLocale is true)
310-
'useSessionLocale' => true,
311-
312-
// Should application use and store the locale stored in a cookie
313-
// if the locale is not defined in the url or the session?
314-
// If true and locale not defined in the url or the session,
315-
// system will take the default locale (defined in config/app.php)
316-
// or the browser preferred locale (if useAcceptLanguageHeader is true)
317-
'useCookieLocale' => true,
318-
319304
// If LaravelLocalizationRedirectFilter is active and hideDefaultLocaleInURL
320305
// is true, the url would not have the default application language
321306
//

0 commit comments

Comments
 (0)