1
0
Fork 0
mirror of https://github.com/archtechx/tenancy.git synced 2025-12-12 14:14:04 +00:00

Make providing identification middleware statically to controllers work (#18)

* Test identification with universal flag with statically provided MW

* Include statically provided controller MW in `tenancy()->getRouteMiddleware()`

* Fix code style (php-cs-fixer)

* Fix PHPStan error

* Test path ID MW and route cloning with statically provided MW

* Create validate.yml

* set continue-on-error to true

* change continue-on-error to fail-fast

* add job name and use if: always()

* update todo

* Update path identification and Fortify integration-related logic (#13)

* Add commented UrlBinding + FortifyRouteTenancy bootstrappers to the config

* Improve FortifyRoute bootstrapper docblock

* Rename bootstrappers

* Complete renaming

* Pass defaults of the original URL generator to the new one

* Fix URL generator-related test (query string id test WIP)

* Fix code style (php-cs-fixer)

* Make Fortify bootstrapper not depend on the UrlGenerator bootstrapper, update comments

* Fix testing UrlGenerator bootstrapper

* Update TenancyUrlGenerator annotations

* Pass tenant parameter manually in Fortify bootstrapper

* Properly test TenancyUrlGenerator functionality

* Get rid of query string in Fortify bootstrapper

* Fix code style (php-cs-fixer)

* Delete outdated comment

* Improve comment

* Improve before/afterEach

* Encourage passing parameters using TenancyUrlGenerator instead of URL::defaults()

* Delete rest of defaulting logic

* Fix code style (php-cs-fixer)

* Delete test group

* Update ForgetTenantParameter docblock

* Update passTenantParameterToRoutes annotation

* Complete todo in test

* Improve test

* Update comment

* Improve comment

* Add keepQueryParameters bool to Fortify bootstrapper

* Test keepQueryParameters

* minor docblock update

* minor docblock changes

* Delete extra import

* Update src/Overrides/TenancyUrlGenerator.php

Co-authored-by: Samuel Štancl <samuel.stancl@gmail.com>

* Improve comment

* Rename test

* Update bypass parameter-related test comments

* Fix merge

* Rename $keepQueryParameters

* Add docblock

* Add comment

* Refactor Fortify bootstrapper

* Fix code style (php-cs-fixer)

* Fix comment

* Skip Fortify bootstrapper test

* minor code improvements

* Improve fortify bootstrapper test

* Add Fortify bootstrapper annotation, improve code

* Fix code style (php-cs-fixer)

* Add commenet

* Complete resource syncing todo (cleanup not needed)

* Delete incorrect namespace

* Complete route context trait name todo

* Fix code style (php-cs-fixer)

---------

Co-authored-by: PHP CS Fixer <phpcsfixer@example.com>
Co-authored-by: Samuel Štancl <samuel.stancl@gmail.com>

* Include statically provided controller MW in `tenancy()->getRouteMiddleware()`

* Fix code style (php-cs-fixer)

* Improve PHPStan error fix

* Include statically provided controller MW in `tenancy()->getRouteMiddleware()`

* Fix PHPStan error

* Fix code style (php-cs-fixer)

* Include statically provided controller MW in `tenancy()->getRouteMiddleware()`

* Fix code style (php-cs-fixer)

---------

Co-authored-by: PHP CS Fixer <phpcsfixer@example.com>
Co-authored-by: Samuel Štancl <samuel.stancl@gmail.com>
This commit is contained in:
lukinovec 2023-12-01 09:38:43 +01:00 committed by GitHub
parent 4953c69fd8
commit e4df597d81
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 128 additions and 11 deletions

View file

@ -7,6 +7,7 @@ namespace Stancl\Tenancy\Concerns;
use Closure; use Closure;
use Illuminate\Contracts\Http\Kernel; use Illuminate\Contracts\Http\Kernel;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Route; use Illuminate\Routing\Route;
use Illuminate\Routing\Router; use Illuminate\Routing\Router;
use Illuminate\Support\Arr; use Illuminate\Support\Arr;
@ -81,6 +82,12 @@ trait DealsWithRouteContexts
public static function getRouteMiddleware(Route $route): array public static function getRouteMiddleware(Route $route): array
{ {
$routeMiddleware = $route->middleware(); $routeMiddleware = $route->middleware();
$controllerClass = $route->getControllerClass();
if ($controllerClass && is_a($controllerClass, HasMiddleware::class, true)) {
$routeMiddleware = array_merge($routeMiddleware, $route->controllerMiddleware());
}
$middlewareGroups = RouteFacade::getMiddlewareGroups(); $middlewareGroups = RouteFacade::getMiddlewareGroups();
$unpackGroupMiddleware = function (array $middleware) use ($middlewareGroups) { $unpackGroupMiddleware = function (array $middleware) use ($middlewareGroups) {
$innerMiddleware = []; $innerMiddleware = [];

View file

@ -0,0 +1,19 @@
<?php
namespace Stancl\Tenancy\Tests\Etc;
use Illuminate\Routing\Controllers\Middleware;
use Illuminate\Routing\Controllers\HasMiddleware;
class HasMiddlewareController implements HasMiddleware
{
public static function middleware()
{
return array_map(fn (string $middleware) => new Middleware($middleware), config('tenancy.static_identification_middleware'));
}
public function index()
{
return tenant() ? 'Tenancy is initialized.' : 'Tenancy is not initialized.';
}
}

View file

@ -5,12 +5,14 @@ declare(strict_types=1);
use Stancl\Tenancy\Tenancy; use Stancl\Tenancy\Tenancy;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Routing\Route; use Illuminate\Routing\Route;
use Stancl\Tenancy\Enums\RouteMode;
use Stancl\Tenancy\Tests\Etc\Tenant; use Stancl\Tenancy\Tests\Etc\Tenant;
use Illuminate\Contracts\Http\Kernel; use Illuminate\Contracts\Http\Kernel;
use Stancl\Tenancy\Actions\CloneRoutesAsTenant;
use Stancl\Tenancy\Resolvers\PathTenantResolver; use Stancl\Tenancy\Resolvers\PathTenantResolver;
use Illuminate\Routing\Controller as BaseController; use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Route as RouteFacade; use Illuminate\Support\Facades\Route as RouteFacade;
use Stancl\Tenancy\Actions\CloneRoutesAsTenant; use Stancl\Tenancy\Tests\Etc\HasMiddlewareController;
use Stancl\Tenancy\Middleware\InitializeTenancyByPath; use Stancl\Tenancy\Middleware\InitializeTenancyByPath;
use Stancl\Tenancy\Middleware\IdentificationMiddleware; use Stancl\Tenancy\Middleware\IdentificationMiddleware;
use Stancl\Tenancy\Resolvers\RequestDataTenantResolver; use Stancl\Tenancy\Resolvers\RequestDataTenantResolver;
@ -24,7 +26,6 @@ use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedByPathException;
use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedOnDomainException; use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedOnDomainException;
use Stancl\Tenancy\Exceptions\MiddlewareNotUsableWithUniversalRoutesException; use Stancl\Tenancy\Exceptions\MiddlewareNotUsableWithUniversalRoutesException;
use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedByRequestDataException; use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedByRequestDataException;
use Stancl\Tenancy\Enums\RouteMode;
test('a route can be universal using domain identification', function (array $routeMiddleware, array $globalMiddleware) { test('a route can be universal using domain identification', function (array $routeMiddleware, array $globalMiddleware) {
foreach ($globalMiddleware as $middleware) { foreach ($globalMiddleware as $middleware) {
@ -42,6 +43,10 @@ test('a route can be universal using domain identification', function (array $ro
: 'Tenancy is not initialized.'; : 'Tenancy is not initialized.';
})->middleware($routeMiddleware); })->middleware($routeMiddleware);
config(['tenancy.static_identification_middleware' => $routeMiddleware]);
RouteFacade::get('/bar', [HasMiddlewareController::class, 'index']);
$tenant = Tenant::create(); $tenant = Tenant::create();
$tenant->domains()->create([ $tenant->domains()->create([
@ -55,6 +60,16 @@ test('a route can be universal using domain identification', function (array $ro
pest()->get("http://{$tenantDomain}/foo") pest()->get("http://{$tenantDomain}/foo")
->assertSuccessful() ->assertSuccessful()
->assertSee('Tenancy is initialized.'); ->assertSee('Tenancy is initialized.');
tenancy()->end();
pest()->get("http://localhost/bar")
->assertSuccessful()
->assertSee('Tenancy is not initialized.');
pest()->get("http://{$tenantDomain}/bar")
->assertSuccessful()
->assertSee('Tenancy is initialized.');
})->with('domain identification types'); })->with('domain identification types');
test('a route can be universal using subdomain identification', function (array $routeMiddleware, array $globalMiddleware) { test('a route can be universal using subdomain identification', function (array $routeMiddleware, array $globalMiddleware) {
@ -72,6 +87,10 @@ test('a route can be universal using subdomain identification', function (array
: 'Tenancy is not initialized.'; : 'Tenancy is not initialized.';
})->middleware($routeMiddleware); })->middleware($routeMiddleware);
config(['tenancy.static_identification_middleware' => $routeMiddleware]);
RouteFacade::get('/bar', [HasMiddlewareController::class, 'index']);
$tenant = Tenant::create(); $tenant = Tenant::create();
$tenantKey = $tenant->getTenantKey(); $tenantKey = $tenant->getTenantKey();
@ -86,6 +105,16 @@ test('a route can be universal using subdomain identification', function (array
pest()->get("http://{$tenantKey}.localhost/foo") pest()->get("http://{$tenantKey}.localhost/foo")
->assertSuccessful() ->assertSuccessful()
->assertSee('Tenancy is initialized.'); ->assertSee('Tenancy is initialized.');
tenancy()->end();
pest()->get("http://localhost/bar")
->assertSuccessful()
->assertSee('Tenancy is not initialized.');
pest()->get("http://{$tenantKey}.localhost/bar")
->assertSuccessful()
->assertSee('Tenancy is initialized.');
})->with('subdomain identification types'); })->with('subdomain identification types');
test('a route can be universal using domainOrSubdomain identification', function (array $routeMiddleware, array $globalMiddleware) { test('a route can be universal using domainOrSubdomain identification', function (array $routeMiddleware, array $globalMiddleware) {
@ -103,6 +132,10 @@ test('a route can be universal using domainOrSubdomain identification', function
: 'Tenancy is not initialized.'; : 'Tenancy is not initialized.';
})->middleware($routeMiddleware); })->middleware($routeMiddleware);
config(['tenancy.static_identification_middleware' => $routeMiddleware]);
RouteFacade::get('/bar', [HasMiddlewareController::class, 'index']);
$tenant = Tenant::create(); $tenant = Tenant::create();
$tenant->domains()->create([ $tenant->domains()->create([
@ -122,10 +155,28 @@ test('a route can be universal using domainOrSubdomain identification', function
->assertSuccessful() ->assertSuccessful()
->assertSee('Tenancy is initialized.'); ->assertSee('Tenancy is initialized.');
tenancy()->end();
// Subdomain identification // Subdomain identification
pest()->get("http://{$tenantSubdomain}.localhost/foo") pest()->get("http://{$tenantSubdomain}.localhost/foo")
->assertSuccessful() ->assertSuccessful()
->assertSee('Tenancy is initialized.'); ->assertSee('Tenancy is initialized.');
tenancy()->end();
pest()->get("http://localhost/bar")
->assertSuccessful()
->assertSee('Tenancy is not initialized.');
pest()->get("http://{$tenantDomain}/bar")
->assertSuccessful()
->assertSee('Tenancy is initialized.');
tenancy()->end();
pest()->get("http://{$tenantSubdomain}.localhost/bar")
->assertSuccessful()
->assertSee('Tenancy is initialized.');
})->with('domainOrSubdomain identification types'); })->with('domainOrSubdomain identification types');
test('a route can be universal using request data identification', function (array $routeMiddleware, array $globalMiddleware) { test('a route can be universal using request data identification', function (array $routeMiddleware, array $globalMiddleware) {
@ -143,6 +194,10 @@ test('a route can be universal using request data identification', function (arr
: 'Tenancy is not initialized.'; : 'Tenancy is not initialized.';
})->middleware($routeMiddleware); })->middleware($routeMiddleware);
config(['tenancy.static_identification_middleware' => $routeMiddleware]);
RouteFacade::get('/bar', [HasMiddlewareController::class, 'index']);
$tenantKey = Tenant::create()->getTenantKey(); $tenantKey = Tenant::create()->getTenantKey();
pest()->get("http://localhost/foo") pest()->get("http://localhost/foo")
@ -152,6 +207,16 @@ test('a route can be universal using request data identification', function (arr
pest()->get("http://localhost/foo?tenant={$tenantKey}") pest()->get("http://localhost/foo?tenant={$tenantKey}")
->assertSuccessful() ->assertSuccessful()
->assertSee('Tenancy is initialized.'); ->assertSee('Tenancy is initialized.');
tenancy()->end();
pest()->get("http://localhost/bar")
->assertSuccessful()
->assertSee('Tenancy is not initialized.');
pest()->get("http://localhost/bar?tenant={$tenantKey}")
->assertSuccessful()
->assertSee('Tenancy is initialized.');
})->with('request data identification types'); })->with('request data identification types');
test('a route can be universal using path identification', function (array $routeMiddleware, array $globalMiddleware) { test('a route can be universal using path identification', function (array $routeMiddleware, array $globalMiddleware) {
@ -169,6 +234,10 @@ test('a route can be universal using path identification', function (array $rout
: 'Tenancy is not initialized.'; : 'Tenancy is not initialized.';
})->middleware($routeMiddleware); })->middleware($routeMiddleware);
config(['tenancy.static_identification_middleware' => $routeMiddleware]);
RouteFacade::get('/bar', [HasMiddlewareController::class, 'index']);
/** @var CloneRoutesAsTenant $cloneRoutesAction */ /** @var CloneRoutesAsTenant $cloneRoutesAction */
$cloneRoutesAction = app(CloneRoutesAsTenant::class); $cloneRoutesAction = app(CloneRoutesAsTenant::class);
@ -183,6 +252,16 @@ test('a route can be universal using path identification', function (array $rout
pest()->get("http://localhost/{$tenantKey}/foo") pest()->get("http://localhost/{$tenantKey}/foo")
->assertSuccessful() ->assertSuccessful()
->assertSee('Tenancy is initialized.'); ->assertSee('Tenancy is initialized.');
tenancy()->end();
pest()->get("http://localhost/bar")
->assertSuccessful()
->assertSee('Tenancy is not initialized.');
pest()->get("http://localhost/{$tenantKey}/bar")
->assertSuccessful()
->assertSee('Tenancy is initialized.');
})->with('path identification types'); })->with('path identification types');
test('correct exception is thrown when route is universal and tenant could not be identified using domain identification', function (array $routeMiddleware, array $globalMiddleware) { test('correct exception is thrown when route is universal and tenant could not be identified using domain identification', function (array $routeMiddleware, array $globalMiddleware) {
@ -322,11 +401,16 @@ test('CloneRoutesAsTenant registers prefixed duplicates of universal routes corr
config(['tenancy.identification.resolvers.' . PathTenantResolver::class . '.tenant_route_name_prefix' => $tenantRouteNamePrefix = 'team-route.']); config(['tenancy.identification.resolvers.' . PathTenantResolver::class . '.tenant_route_name_prefix' => $tenantRouteNamePrefix = 'team-route.']);
// Test that routes with controllers as well as routes with closure actions get cloned correctly // Test that routes with controllers as well as routes with closure actions get cloned correctly
$universalRoute = RouteFacade::get('/home', $useController ? Controller::class : fn () => tenant() ? 'Tenancy initialized.' : 'Tenancy not initialized.')->middleware($routeMiddleware)->name('home'); $universalRoute = RouteFacade::get('/home', $useController ? Controller::class : fn () => tenant() ? 'Tenancy is initialized.' : 'Tenancy is not initialized.')->middleware($routeMiddleware)->name('home');
$centralRoute = RouteFacade::get('/central', fn () => true)->name('central'); $centralRoute = RouteFacade::get('/central', fn () => true)->name('central');
expect($routes = RouteFacade::getRoutes()->get())->toContain($universalRoute); config(['tenancy.static_identification_middleware' => $routeMiddleware]);
expect($routes)->toContain($centralRoute);
$universalRoute2 = RouteFacade::get('/bar', [HasMiddlewareController::class, 'index'])->name('second-home');
expect($routes = RouteFacade::getRoutes()->get())->toContain($universalRoute)
->toContain($universalRoute2)
->toContain($centralRoute);
/** @var CloneRoutesAsTenant $cloneRoutesAction */ /** @var CloneRoutesAsTenant $cloneRoutesAction */
$cloneRoutesAction = app(CloneRoutesAsTenant::class); $cloneRoutesAction = app(CloneRoutesAsTenant::class);
@ -337,19 +421,26 @@ test('CloneRoutesAsTenant registers prefixed duplicates of universal routes corr
->toContain($universalRoute) ->toContain($universalRoute)
->toContain($centralRoute); ->toContain($centralRoute);
$newRoute = collect($routesAfterRegisteringDuplicates)->filter(fn ($route) => ! in_array($route, $routes))->first(); $newRoutes = collect($routesAfterRegisteringDuplicates)->filter(fn ($route) => ! in_array($route, $routes));
expect($newRoute->uri())->toBe('{' . $tenantParameterName . '}' . '/' . $universalRoute->uri()); expect($newRoutes->first()->uri())->toBe('{' . $tenantParameterName . '}' . '/' . $universalRoute->uri());
expect($newRoutes->last()->uri())->toBe('{' . $tenantParameterName . '}' . '/' . $universalRoute2->uri());
expect(tenancy()->getRouteMiddleware($newRoute))->toBe(array_merge(tenancy()->getRouteMiddleware($universalRoute), ['tenant'])); expect(tenancy()->getRouteMiddleware($newRoutes->first()))->toBe(array_merge(tenancy()->getRouteMiddleware($universalRoute), ['tenant']));
expect(tenancy()->getRouteMiddleware($newRoutes->last()))->toBe(array_merge(tenancy()->getRouteMiddleware($universalRoute2), ['tenant']));
$tenant = Tenant::create(); $tenant = Tenant::create();
pest()->get(route($centralRouteName = $universalRoute->getName()))->assertSee('Tenancy not initialized.'); pest()->get(route($centralRouteName = $universalRoute->getName()))->assertSee('Tenancy is not initialized.');
pest()->get(route($tenantRouteName = $newRoute->getName(), [$tenantParameterName => $tenant->getTenantKey()]))->assertSee('Tenancy initialized.'); pest()->get(route($centralRouteName2 = $universalRoute2->getName()))->assertSee('Tenancy is not initialized.');
pest()->get(route($tenantRouteName = $newRoutes->first()->getName(), [$tenantParameterName => $tenant->getTenantKey()]))->assertSee('Tenancy is initialized.');
tenancy()->end();
pest()->get(route($tenantRouteName2 = $newRoutes->last()->getName(), [$tenantParameterName => $tenant->getTenantKey()]))->assertSee('Tenancy is initialized.');
expect($tenantRouteName)->toBe($tenantRouteNamePrefix . $universalRoute->getName()); expect($tenantRouteName)->toBe($tenantRouteNamePrefix . $universalRoute->getName());
expect($tenantRouteName2)->toBe($tenantRouteNamePrefix . $universalRoute2->getName());
expect($centralRouteName)->toBe($universalRoute->getName()); expect($centralRouteName)->toBe($universalRoute->getName());
expect($centralRouteName2)->toBe($universalRoute2->getName());
})->with([ })->with([
'kernel identification' => true, 'kernel identification' => true,
'route-level identification' => false, 'route-level identification' => false,
@ -519,7 +610,7 @@ class Controller extends BaseController
{ {
public function __invoke() public function __invoke()
{ {
return tenant() ? 'Tenancy initialized.' : 'Tenancy not initialized.'; return tenant() ? 'Tenancy is initialized.' : 'Tenancy is not initialized.';
} }
} }