Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.4] Localize routes #16541

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 85 additions & 0 deletions src/Illuminate/Routing/Middleware/Localize.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<?php

namespace Illuminate\Routing\Middleware;

use Closure;
use Illuminate\Foundation\Application;
use Illuminate\Contracts\Routing\UrlGenerator;

class Localize
{
/**
* The application instance.
*
* @var \Illuminate\Foundation\Application
*/
protected $app;

/**
* The URL generator instance.
*
* @var \Illuminate\Contracts\Routing\UrlGenerator
*/
protected $url;

/**
* Create a new request localizer.
*
* @param \Illuminate\Foundation\Application $app
* @param \Illuminate\Contracts\Routing\UrlGenerator $url
* @return void
*/
public function __construct(Application $app, UrlGenerator $url)
{
$this->app = $app;
$this->url = $url;
}

/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$defaultLocale = $this->app['config']->get('app.fallback_locale');

if (! $locale = $this->getLocaleFromRequest($request)) {
return redirect(trim($defaultLocale.'/'.$request->path(), '/'));
}

$this->app->setLocale($locale);

$this->url->formatPathUsing(function ($path) use ($locale) {
return rtrim('/'.$locale.$path, '/');
});

return $next($request);
}

/**
* Extract the locale from the given request.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
private function getLocaleFromRequest($request)
{
if ($this->localeIsValid($locale = $request->segment(1))) {
return $locale;
}
}

/**
* Determine if the given locale is valid.
*
* @param string $locale
* @return bool
*/
private function localeIsValid($locale)
{
return in_array($locale, $this->app['config']->get('app.locales'));
}
}
16 changes: 16 additions & 0 deletions src/Illuminate/Routing/Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,22 @@ public function resource($name, $controller, array $options = [])
$registrar->register($name, $controller, $options);
}

/**
* Localize the registered routes.
*
* @return void
*/
public function localize()
{
if ($this->container && $this->container->bound('Illuminate\Routing\RoutesLocalizer')) {
$localizer = $this->container->make('Illuminate\Routing\RoutesLocalizer');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should the current Router instance be passed here as well?

} else {
$localizer = new RoutesLocalizer($this, $this->container['config']);
}

$localizer->localize();
}

/**
* Register the typical authentication routes for an application.
*
Expand Down
88 changes: 88 additions & 0 deletions src/Illuminate/Routing/RoutesLocalizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?php

namespace Illuminate\Routing;

use Illuminate\Contracts\Config\Repository;

class RoutesLocalizer
{
/**
* The router instance.
*
* @var \Illuminate\Routing\Router
*/
protected $router;

/**
* The configuration repository instance.
*
* @var \Illuminate\Routing\Router
*/
protected $config;

/**
* Create a new routes localizer instance.
*
* @param \Illuminate\Routing\Router $router
* @param \Illuminate\Contracts\Config\Repository $config
* @return void
*/
public function __construct(Router $router, Repository $config)
{
$this->router = $router;
$this->config = $config;
}

/**
* Localize routes using the given locales.
*
* @return void
*/
public function localize()
{
foreach ($this->router->getRoutes() as $route) {
if (! $this->routeShouldBeLocalized($route)) {
return;
}

foreach ($this->config->get('app.locales') as $locale) {
$this->addRouteForLocale($route, $locale);
}
}
}

/**
* Add a route for the locale in the route collection.
*
* @param \Illuminate\Routing\Route $route
* @param string $locale
* @return void
*/
private function addRouteForLocale($route, $locale)
{
$route = clone $route;

$routeUri = $route->getUri();

$route->setUri(
$routeUri == '/' ? $locale : $locale.'/'.$routeUri
);

if ($route->getName()) {
$route->name('.'.$locale);
}

$this->router->getRoutes()->add($route);
}

/**
* Determine if the route should be localized.
*
* @param \Illuminate\Routing\Route $route
* @return bool
*/
private function routeShouldBeLocalized($route)
{
return in_array('localize', $route->gatherMiddleware());
}
}
101 changes: 101 additions & 0 deletions tests/Routing/RouteLocalizationTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
<?php

use Illuminate\Http\Request;
use Illuminate\Routing\Router;
use Illuminate\Events\Dispatcher;
use Illuminate\Foundation\Application;

class RouteLocalizationTest extends PHPUnit_Framework_TestCase
{
/**
* @var Application
*/
protected $app;
protected $url;

public function setup()
{
$this->app = new Application();
}

public function testLocalizerMatchesRouteWithLocale()
{
$router = $this->getRouter();

$router->get('foo', function () {
return 'foo';
})->middleware('localize');

$this->app['config']->shouldReceive('get')->with('app.locales')->andReturn(['en', 'ar']);
$this->app['config']->shouldReceive('get')->with('app.fallback_locale')->andReturn('en');

$this->app['config']->shouldReceive('set')->with('app.locale', 'ar');
$this->app['translator']->shouldReceive('setLocale')->with('ar');

$this->app['config']->shouldReceive('set')->with('app.locale', 'en');
$this->app['translator']->shouldReceive('setLocale')->with('en');

$this->url->shouldReceive('formatPathUsing');

$router->localize();

$this->assertEquals('foo', $router->dispatch(Request::create('ar/foo', 'GET'))->getContent());
$this->assertEquals('foo', $router->dispatch(Request::create('en/foo', 'GET'))->getContent());
}

/**
* @expectedException Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function testLocalizerDoesntLocalizeRoutesWithoutTheMiddleware()
{
$router = $this->getRouter();

$router->get('foo', function () {
return 'foo';
});

$router->localize();

$this->assertEquals('foo', $router->dispatch(Request::create('ar/foo', 'GET'))->getContent());
}

public function testLocalizerRedirectesToPathWithDefaultLocale()
{
$router = $this->getRouter();

$redirector = Mockery::mock('Illuminate\Routing\Redirector');
$redirector->shouldReceive('to')->once()->with('en/foo', 302, [], null);

$this->app->bind('redirect', function () use ($redirector) {
return $redirector;
});

$this->app['config']->shouldReceive('get')->with('app.fallback_locale')->andReturn('en');
$this->app['config']->shouldReceive('get')->with('app.locales')->andReturn(['en', 'ar']);

$router->get('foo', function () {
return 'foo';
})->middleware('localize');

$router->dispatch(Request::create('foo', 'GET'));
}

protected function getRouter()
{
$this->url = Mockery::mock('Illuminate\Contracts\Routing\UrlGenerator');

$this->app['config'] = Mockery::mock('Illuminate\Contracts\Config\Repository');

$this->app['translator'] = Mockery::mock('Illuminate\Translation\Translator');

$this->app->bind('Illuminate\Contracts\Routing\UrlGenerator', function () {
return $this->url;
});

$router = new Router(new Dispatcher, $this->app);

$router->middleware('localize', 'Illuminate\Routing\Middleware\Localize');

return $router;
}
}