Skip to content

Instantly share code, notes, and snippets.

@overtrue overtrue/SetLocale.php
Last active Aug 6, 2017

Embed
What would you like to do?
常用组件
<?php
namespace App\Http\Middleware;
use App;
use Closure;
use Illuminate\Http\Response;
class SetLocale
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$locale = $request->cookie('locale', 'zh-CN');
if ($request->has('locale')) {
$locale = $request->get('locale');
}
App::setLocale($locale);
$cookie = cookie('locale', $locale);
$docsUrlRegex = '~docs/(?<version>\w+)(?:/(?<locale>zh-CN|en)?/?)?~';
if (preg_match($docsUrlRegex, $request->path(), $matches)) {
$currentLocale = trim($matches['locale'] ?? 'zh-CN', '/');
$version = $matches['version'] ?? 'master';
if ($currentLocale !== $locale) {
return redirect(preg_replace($docsUrlRegex, "docs/{$version}/{$locale}/", $request->fullUrl()));
}
}
$response = $next($request);
if ($response instanceof Response) {
$response->cookie($cookie);
}
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.