From e4df597d81497d8ad954fbb2a1fbdab8198322f0 Mon Sep 17 00:00:00 2001 From: lukinovec Date: Fri, 1 Dec 2023 09:38:43 +0100 Subject: [PATCH] Make providing identification middleware statically to controllers work (#18) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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 * 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 Co-authored-by: Samuel Štancl * 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 Co-authored-by: Samuel Štancl --- src/Concerns/DealsWithRouteContexts.php | 7 ++ tests/Etc/HasMiddlewareController.php | 19 ++++ tests/UniversalRouteTest.php | 113 +++++++++++++++++++++--- 3 files changed, 128 insertions(+), 11 deletions(-) create mode 100644 tests/Etc/HasMiddlewareController.php diff --git a/src/Concerns/DealsWithRouteContexts.php b/src/Concerns/DealsWithRouteContexts.php index 4246fcb3..e015848c 100644 --- a/src/Concerns/DealsWithRouteContexts.php +++ b/src/Concerns/DealsWithRouteContexts.php @@ -7,6 +7,7 @@ namespace Stancl\Tenancy\Concerns; use Closure; use Illuminate\Contracts\Http\Kernel; use Illuminate\Http\Request; +use Illuminate\Routing\Controllers\HasMiddleware; use Illuminate\Routing\Route; use Illuminate\Routing\Router; use Illuminate\Support\Arr; @@ -81,6 +82,12 @@ trait DealsWithRouteContexts public static function getRouteMiddleware(Route $route): array { $routeMiddleware = $route->middleware(); + $controllerClass = $route->getControllerClass(); + + if ($controllerClass && is_a($controllerClass, HasMiddleware::class, true)) { + $routeMiddleware = array_merge($routeMiddleware, $route->controllerMiddleware()); + } + $middlewareGroups = RouteFacade::getMiddlewareGroups(); $unpackGroupMiddleware = function (array $middleware) use ($middlewareGroups) { $innerMiddleware = []; diff --git a/tests/Etc/HasMiddlewareController.php b/tests/Etc/HasMiddlewareController.php new file mode 100644 index 00000000..27fb82a8 --- /dev/null +++ b/tests/Etc/HasMiddlewareController.php @@ -0,0 +1,19 @@ + new Middleware($middleware), config('tenancy.static_identification_middleware')); + } + + public function index() + { + return tenant() ? 'Tenancy is initialized.' : 'Tenancy is not initialized.'; + } +} diff --git a/tests/UniversalRouteTest.php b/tests/UniversalRouteTest.php index 18ea330d..81d3171a 100644 --- a/tests/UniversalRouteTest.php +++ b/tests/UniversalRouteTest.php @@ -5,12 +5,14 @@ declare(strict_types=1); use Stancl\Tenancy\Tenancy; use Illuminate\Http\Request; use Illuminate\Routing\Route; +use Stancl\Tenancy\Enums\RouteMode; use Stancl\Tenancy\Tests\Etc\Tenant; use Illuminate\Contracts\Http\Kernel; +use Stancl\Tenancy\Actions\CloneRoutesAsTenant; use Stancl\Tenancy\Resolvers\PathTenantResolver; use Illuminate\Routing\Controller as BaseController; 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\IdentificationMiddleware; use Stancl\Tenancy\Resolvers\RequestDataTenantResolver; @@ -24,7 +26,6 @@ use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedByPathException; use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedOnDomainException; use Stancl\Tenancy\Exceptions\MiddlewareNotUsableWithUniversalRoutesException; use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedByRequestDataException; -use Stancl\Tenancy\Enums\RouteMode; test('a route can be universal using domain identification', function (array $routeMiddleware, array $globalMiddleware) { foreach ($globalMiddleware as $middleware) { @@ -42,6 +43,10 @@ test('a route can be universal using domain identification', function (array $ro : 'Tenancy is not initialized.'; })->middleware($routeMiddleware); + config(['tenancy.static_identification_middleware' => $routeMiddleware]); + + RouteFacade::get('/bar', [HasMiddlewareController::class, 'index']); + $tenant = Tenant::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") ->assertSuccessful() ->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'); 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.'; })->middleware($routeMiddleware); + config(['tenancy.static_identification_middleware' => $routeMiddleware]); + + RouteFacade::get('/bar', [HasMiddlewareController::class, 'index']); + $tenant = Tenant::create(); $tenantKey = $tenant->getTenantKey(); @@ -86,6 +105,16 @@ test('a route can be universal using subdomain identification', function (array pest()->get("http://{$tenantKey}.localhost/foo") ->assertSuccessful() ->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'); 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.'; })->middleware($routeMiddleware); + config(['tenancy.static_identification_middleware' => $routeMiddleware]); + + RouteFacade::get('/bar', [HasMiddlewareController::class, 'index']); + $tenant = Tenant::create(); $tenant->domains()->create([ @@ -122,10 +155,28 @@ test('a route can be universal using domainOrSubdomain identification', function ->assertSuccessful() ->assertSee('Tenancy is initialized.'); + tenancy()->end(); + // Subdomain identification pest()->get("http://{$tenantSubdomain}.localhost/foo") ->assertSuccessful() ->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'); 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.'; })->middleware($routeMiddleware); + config(['tenancy.static_identification_middleware' => $routeMiddleware]); + + RouteFacade::get('/bar', [HasMiddlewareController::class, 'index']); + $tenantKey = Tenant::create()->getTenantKey(); 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}") ->assertSuccessful() ->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'); 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.'; })->middleware($routeMiddleware); + config(['tenancy.static_identification_middleware' => $routeMiddleware]); + + RouteFacade::get('/bar', [HasMiddlewareController::class, 'index']); + /** @var CloneRoutesAsTenant $cloneRoutesAction */ $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") ->assertSuccessful() ->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'); 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.']); // 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'); - expect($routes = RouteFacade::getRoutes()->get())->toContain($universalRoute); - expect($routes)->toContain($centralRoute); + config(['tenancy.static_identification_middleware' => $routeMiddleware]); + + $universalRoute2 = RouteFacade::get('/bar', [HasMiddlewareController::class, 'index'])->name('second-home'); + + expect($routes = RouteFacade::getRoutes()->get())->toContain($universalRoute) + ->toContain($universalRoute2) + ->toContain($centralRoute); /** @var CloneRoutesAsTenant $cloneRoutesAction */ $cloneRoutesAction = app(CloneRoutesAsTenant::class); @@ -337,19 +421,26 @@ test('CloneRoutesAsTenant registers prefixed duplicates of universal routes corr ->toContain($universalRoute) ->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(); - pest()->get(route($centralRouteName = $universalRoute->getName()))->assertSee('Tenancy not initialized.'); - pest()->get(route($tenantRouteName = $newRoute->getName(), [$tenantParameterName => $tenant->getTenantKey()]))->assertSee('Tenancy initialized.'); + pest()->get(route($centralRouteName = $universalRoute->getName()))->assertSee('Tenancy is not 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($tenantRouteName2)->toBe($tenantRouteNamePrefix . $universalRoute2->getName()); expect($centralRouteName)->toBe($universalRoute->getName()); + expect($centralRouteName2)->toBe($universalRoute2->getName()); })->with([ 'kernel identification' => true, 'route-level identification' => false, @@ -519,7 +610,7 @@ class Controller extends BaseController { public function __invoke() { - return tenant() ? 'Tenancy initialized.' : 'Tenancy not initialized.'; + return tenant() ? 'Tenancy is initialized.' : 'Tenancy is not initialized.'; } }