Skip to content

Commit

Permalink
Added localizedRoute function
Browse files Browse the repository at this point in the history
  • Loading branch information
andrey-helldar committed Jul 10, 2024
1 parent 8de8edf commit 644c389
Show file tree
Hide file tree
Showing 5 changed files with 76 additions and 27 deletions.
5 changes: 4 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,10 @@
"autoload": {
"psr-4": {
"LaravelLang\\Routes\\": "src/"
}
},
"files": [
"helpers/functions.php"
]
},
"autoload-dev": {
"psr-4": {
Expand Down
25 changes: 25 additions & 0 deletions helpers/functions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

declare(strict_types=1);

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
use LaravelLang\Config\Facades\Config;

if (! function_exists('localizedRoute')) {
function localizedRoute(string $route, array $parameters = [], bool $absolute = true): string
{
$locale = Config::shared()->routes->names->parameter;
$prefix = Config::shared()->routes->namePrefix;

$name = Str::start($route, $prefix);

if (! Route::has($name)) {
return route($route, $parameters, $absolute);
}

return route($name, array_merge([
$locale => app()->getLocale(),
], $parameters), $absolute);
}
}
18 changes: 18 additions & 0 deletions ide.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"$schema": "https://laravel-ide.com/schema/laravel-ide-v2.json",
"completions": [
{
"complete": "routeName",
"condition": [
{
"functionNames": [
"localizedRoute"
],
"parameters": [
1
]
}
]
}
]
}
29 changes: 29 additions & 0 deletions tests/Unit/Helpers/LocalizedRouteTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

declare(strict_types=1);

use LaravelLang\Config\Facades\Config;
use Tests\Constants\LocaleValue;

test('route groups', function () {
$name = Config::shared()->routes->namePrefix;
$locale = LocaleValue::LocaleMain;
$fallback = LocaleValue::LocaleAliasParent;

expect(localizedRoute($name . 'via.group.facade', ['foo' => 'bar']))
->toEndWith("localhost/$locale/group/facade/bar");

expect(localizedRoute($name . 'via.group.macro', ['foo' => 'bar', 'locale' => $fallback]))
->toEndWith("localhost/$fallback/group/macro/bar");

expect(localizedRoute('via.group.facade', ['foo' => 'bar']))
->toEndWith("localhost/$locale/group/facade/bar");

expect(localizedRoute('via.group.macro', ['foo' => 'bar', 'locale' => $fallback]))
->toEndWith("localhost/$fallback/group/macro/bar");
});

test('routes without groups', function () {
expect(localizedRoute('via.model.default', ['foo' => 'bar']))
->toEndWith('localhost/model/default/bar');
});
26 changes: 0 additions & 26 deletions tests/Unit/Services/UrlGeneratorTest.php

This file was deleted.

0 comments on commit 644c389

Please sign in to comment.