Skip to content
Merged
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
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"license": "MIT",
"require": {
"php": "^8.2",
"codedor/laravel-locale-collection": "^0.0.2",
"codedor/laravel-locale-collection": "^0.0.3",
"illuminate/contracts": "^10.0",
"spatie/laravel-package-tools": "^1.12"
},
Expand Down
10 changes: 6 additions & 4 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.0/phpunit.xsd" backupGlobals="false" bootstrap="vendor/autoload.php" colors="true" processIsolation="false" stopOnFailure="false" executionOrder="random" failOnWarning="true" failOnRisky="true" failOnEmptyTestSuite="true" beStrictAboutOutputDuringTests="true" cacheDirectory=".phpunit.cache" backupStaticProperties="false">
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.1/phpunit.xsd" backupGlobals="false" bootstrap="vendor/autoload.php" colors="true" processIsolation="false" stopOnFailure="false" executionOrder="random" failOnWarning="true" failOnRisky="true" failOnEmptyTestSuite="true" beStrictAboutOutputDuringTests="true" cacheDirectory=".phpunit.cache" backupStaticProperties="false">
<testsuites>
<testsuite name="Codedor Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
<coverage>
<include>
<directory suffix=".php">./src</directory>
</include>
<report>
<html outputDirectory="build/coverage"/>
<text outputFile="build/coverage.txt"/>
Expand All @@ -21,4 +18,9 @@
<php>
<server name="APP_KEY" value="base64:llrAPMQL0x08EHCBwf/UkOqptL7p/SXkcTnY2znWurE="/>
</php>
<source>
<include>
<directory suffix=".php">./src</directory>
</include>
</source>
</phpunit>
11 changes: 9 additions & 2 deletions src/Providers/TranslatableRoutesServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Codedor\TranslatableRoutes\TranslateRoute;
use Illuminate\Routing\Route as RoutingRoute;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
use Spatie\LaravelPackageTools\Package;
use Spatie\LaravelPackageTools\PackageServiceProvider;

Expand All @@ -22,19 +23,25 @@ public function configurePackage(Package $package): void

public function bootingPackage()
{
Locale::macro('routePrefix', function (): string {
/** @var Locale $this */
return Str::lower($this->locale());
});

LocaleCollection::macro('registerRoutes', function (Closure|array|string $callback): void {
/** @var LocaleCollection $this */
$this->each(fn (Locale $locale) => Route::middleware('translatable')
->domain($locale->url())
->where(['locale' => $locale->locale()])
->where(['translatable_prefix' => $locale->routePrefix()])
->prefix('/' . $locale->urlLocale())
->as($locale->routePrefix() . '.')
->group($callback)
);

collect(Route::getRoutes()->getRoutes())
->filter(fn (RoutingRoute $route) => in_array('translatable', $route->middleware()))
->each(function (RoutingRoute $route) {
$locale = $this->firstLocale($route->wheres['locale'] ?? '');
$locale = $this->firstWhere(fn (Locale $locale) => Str::startsWith($route->getName(), $locale->routePrefix()));

if (! $locale) {
return;
Expand Down
16 changes: 10 additions & 6 deletions src/TranslateRoute.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,11 @@
use Codedor\LocaleCollection\LocaleCollection as TranslatableRoutesLocaleCollection;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;

class TranslateRoute
{
public static function forName(string $routeName, string $locale = null, array|Collection $parameters = []): string
public static function forName(string $routeName, string $locale = null, array|Collection $parameters = []): ?string
{
if (! $locale) {
$locale = app()->getLocale();
Expand All @@ -22,11 +21,16 @@ public static function forName(string $routeName, string $locale = null, array|C

app('url')->forceRootUrl($localeObject->url());

$route = collect(Route::getRoutes()->getRoutes())
->filter(fn ($route) => $route->getName() === $routeName && $route->wheres['locale'] === $locale)
->first();
try {
return route(
"{$localeObject->routePrefix()}.{$routeName}",
self::translateParameters($parameters, $localeObject)
);
} catch (\Throwable $th) {
report($th);

return app('url')->toRoute($route, self::translateParameters($parameters, $localeObject), true);
return null;
}
}

public static function getAllForNameOrCurrent(string $routeName = null, array $parameters = []): TranslatableRoutesLocaleCollection
Expand Down
2 changes: 1 addition & 1 deletion src/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
use Illuminate\Support\Collection;

if (! function_exists('translate_route')) {
function translate_route(string $routeName, string $locale = null, array|Collection $parameters = []): string
function translate_route(string $routeName, string $locale = null, array|Collection $parameters = []): ?string
{
return TranslateRoute::forName($routeName, $locale, $parameters);
}
Expand Down
6 changes: 2 additions & 4 deletions tests/Feature/LocaleCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,8 @@
->getName()->toBe('non-translatable')
->wheres->toBe([]),
fn ($route) => $route
->getName()->toBe('home')
->wheres->toBe(['locale' => 'nl-BE']),
->getName()->toBe('nl-be.home'),
fn ($route) => $route
->getName()->toBe('home')
->wheres->toBe(['locale' => 'fr-BE'])
->getName()->toBe('fr-be.home')
);
});
43 changes: 43 additions & 0 deletions tests/Feature/RouteCompileTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

use Codedor\LocaleCollection\Facades\LocaleCollection;
use Codedor\LocaleCollection\Locale;
use Codedor\TranslatableRoutes\Tests\TestEnums\TestCategory;
use Codedor\TranslatableRoutes\Tests\TestModels\TestPage;
use Illuminate\Support\Facades\Route;

beforeEach(function () {
LocaleCollection::push(new Locale('nl', 'http://codedor.be'))
->push(new Locale('fr-BE', 'http://codedor.be', 'fr'))
->push(new Locale('en-GB', 'http://codedor.com'));

LocaleCollection::registerRoutes(function () {
Route::get('', function () {
return translated_routes();
})->name('home');

Route::get('/page/{page:slug}', function () {
return translated_routes();
})->name('page');

Route::get('/category/{category}', function (TestCategory $category) {
return translated_routes();
})->name('enum');
});

$this->page = TestPage::first();
});

// calling route:cache does not work in tests, so we have to test the compiled routes manually
it('can compile routes', function () {
$routes = tap(app('router')->getRoutes(), function ($routes) {
$routes->refreshNameLookups();
$routes->refreshActionLookups();
});

foreach ($routes as $route) {
$route->prepareForSerialization();
}

expect($routes->compile())->toBeArray();
});