mirror of
https://github.com/archtechx/tenancy.git
synced 2025-12-12 23:34:03 +00:00
Central routes without Route::domain(), configurable tenant/central routes by default for domain/subdomain identification, allow accessing central routes in early identification for path & request data middleware (#3)
* Update url binding bootstrapper test * Fix parent::temporarySignedRoute() call * Add universal route tests for all identification types * Improve determineContextFromRequest() * Add setting `TenancyUrlGenerator::$prefixRouteNames` to true in TSP stub * Delete seemingly redundant test (making one route universal won't make all routes universal in any case) * Use collection syntax in ReregisterUniversalRoutes * Improve comments * Add domain identification MW annotation * Update condition in GloballyUsable * Set `tenancy.bootstrappers` instead of adding the bootstrappers using `tenancy.bootstrappers.x`, move test * Revert GloballyUsable condition change * Delete assigning bootstrappers to tenancy.bootstrappers.x * Exclude cache prefixing bootstrapper from the initial configuration * Fix test * Unset bypass parameter * Set static kernel identification-related properties in TestCase * Update bootstrapper name in annotation * Move unset() into a condition * Update TenancyUrlGenerator condition * Set static properties without instantiating Tenancy * Fix unsetting bypass parameter * formatting changes * add a comment * improve docblock * add docblock to TenancyUrlGenerator [ci skip] * docblock changes [ci skip] * Update TenancyUrlGenerator (rename variable, allow bypassing prefixing temporarySignedRoute name) * Improve determineContextFromRequest * Only return the new url generator instance when extending 'url' in UrlBindingBootstrapper * Check route's MW groups for the path ID MW * Remove extra imports from config * Rename MiddlewareContext to Context, add condition for skipping ID MW * Set only the needed bootstrappers in TestCase * Fix code style (php-cs-fixer) * Remove condition * Use correct return type * Fix PHPStan issue * Update comment * Check for tenant parameter instead of prefix * Update shouldBeSkipped condition for universal routes * Don't remove the 'universal' MW group after route re-registration, update test * Fix code style (php-cs-fixer) * Fix typo * Add test for mixing placement of access prevention and identification MW * Add test for mixing placement of access prevention and identification MW * Update docblock * Add setting the session and key resolvers in UrlBindingBootstrapper (required with LW file uploads) * Update stub * Update variable name in route reregistering action * Add trailing comma * Fix code style (php-cs-fixer) * Require routes using path identification to be flagged as tenant in order to be recognized as tenant routes * Add tenant flag while re-registering routes * Update determineContextFromRequest condition (wip) * Fix code style (php-cs-fixer) * Update the middleware context logic so that universal routes have to be flagged as tenant instead of just having ID MW * Update path identification condition * Fix re-registering the LW localized route (add 'tenant' MW) * Update docblock * Simplify LW route re-registration * Add comment * Update comment * Simplify determineContextFromRequest, add comment * Improve stub * Add skipRoute method + test * Fix typo * Update assets/TenancyServiceProvider.stub.php * Update src/Concerns/DealsWithEarlyIdentification.php * Fix typo Co-authored-by: Samuel Štancl <samuel.stancl@gmail.com> * Improve comment * Update test structure * Restructure Fortify test * code style * Fix typo * Update ReregisterUniversalRoutes annotation * Only prefix route name if it wasn't already prefixed * Add todo@docs * Delete `Tenancy::$kernelAccessPreventionSkipped` and related logic * Delete test tenant cleanup * Test MW group unpacking, restructure and improve test * Test that tenancy isn't initialized after visiting a central route with the tenant parameter * Delete "in both central and tenant contexts" from test names * Test that re-registering works with controllers too * Set misc route properties during re-registering * Determine context instead of guessing, update universal route tests * Use randomly generated tenant ID instead of hardcoding `acme` * Remove setting route validators * Rename and update determine context method, add comments * Update ForgetTenantParameter annotation * Add comment * Delete comment, delete variable assignment * Update early domain identification test * Improve domain identification tests (test defaulting accurately) * Improve readability * Simplify domain early ID test * Use randomly generated tenant instead of 'acme' * Simplify request data ID test, use random tenant instead of 'acme' * Simplify defaulting domain identification test * Use RouteFacade alias for the Route facade, improve test code * Add defaulting to the request data and path ID tests * Merge path identification tenant parameter removal tests, clean up * Correct wording Co-authored-by: Samuel Štancl <samuel.stancl@gmail.com> * Delete debugging things from UniversalRouteTest * Update annotation * Add `// Creates a matrix` * Improve comment wording * Add MiddlewareUsableWithUniversalRoutes, refactor code accordingly * Fix code style (php-cs-fixer) * Delete debugging leftovers * Delete unused import * Update universal route GloballyUsable condition * Don't implement the universal route interface in access prevention MW * Check if request host is in the central domains in domain ID MW * Test universal routes with domain identification without access prevent MW * Test that universal routes work only with identification MW implementing the universal route interface * Fix code style (php-cs-fixer) * Rename GloballyUsable to UsableWithEarlyIdentification * Fix annotation * Update requestHasTenant annotations * Update comment * Add `with()` comments * Add with() comments where missing * Rename interface, update/add comments * Rename exception, update its default message * Fix code style (php-cs-fixer) * Fix interface name * Delete redundant code from subdomain ID MW * Change domainOrSubdomain ID MW so that instead of passing the identification to other MWs, it happens in the domainOrSubdomain MW * Test domainOrSubdomain identification with universal routes * Fix code style (php-cs-fixer) * Rename universal routes interface * Fix code style (php-cs-fixer) * Try explaining forgetting the tenant parameter better * update interface name reference * uncouple example from query parameters * Update ForgetTenantParameter.php * Update ForgetTenantParameter annotation * Check both routeHasMiddleware and routeHasIdentificationMiddleware in the route MW detection test * Hardcode tenant subdomain * Delete redundant event listening code * Delete unused imports * Delete misuse of `tenancy()->getMiddlewareContext()` from conditions * Delete unused variable * Update comment * Correct request data identification test (defaulting) * Fix defaulting in path id test * Move default route context configuration in domian id test * Rename and update the tenant parameter test * Delete extra tenant parameter test * Use `tenant-domain.test` instead of `127.0.0.2` * Add `default_to_universal_routes` config key * Deal with defaulting to universal routes in the reregistering action * Update logic to make defaulting to universal routes possible * Test defaulting to universal routes * Fix code style (php-cs-fixer) * Delete extra tests * Delete "without access prevention" from datasets * Add defaulting to universal routes to datasets * Override universal flag by central/tenant flag * Add universal flag overriding test * Update "a route can be universal in both route modes" so that the name corresponds with the tested thing * Ignore the PHPStan error * Reset `InitializeTenancyByPath::$onFail` in PathIdentificationTest * Simplify expression * Use 'Tenancy (not) initialized.' in instead of `tenant()?->getTenantKey()` for better assertions * Properly test removing tenant parameter * Reset static properties in tests * Correct comments in EarlyIdentificationTest * Add comment * Add detail to annotation * Throw exception if payload isn't string or null in request data ID MW * Fix code style (php-cs-fixer) * Delete static `$kernelIdentificationSkipped` property, use `$request->attributes` instead * Use 'default_route_mode' instead of 'default_to_tenant/universal_routes' * Fix code style (php-cs-fixer) * Make path identification MW, tenantParameterName and tenantRouteNamePrefix configurable in ReregisterUniversalRoutes * Delete unused import * Add `$passTenantParameterToRoute` to TenancyUrlGenerator * Use `$passTenantParameterToRoute` in BootstrapperTest * Bypass tenant parameter passing * Improve TenancyUrlGenerator so that both ID methods work * Fix code style (php-cs-fixer) * Improve TenancyUrlGenerator readability * Add modifyBehavior() to TenancyUrlGenerator * Fix code style (php-cs-fixer) * Improve comment * Toggle route name prefixing in path/request data ID MW (route-level identification) * Fix code style (php-cs-fixer) * Add path identification MW config key, add `getTenantParameterName()` to ForgetTenantParameter * Fix code style (php-cs-fixer) * Fix modifyBehavior and routeBehaviorModificationBypassed * Add type to `$parameters` parameter * Split modifyBehavior into two methods, don't pass name and parameters by reference * Update UrlBindingBootstrapper annotation * Correct naming in tests (request data -> query string identification) * Add info to annotation * Pass arrays to the behavior modification methods instead of `mixed` * Fix default value of static property in Fortify bootstrapper * Fix code style (php-cs-fixer) * Correct annotation * Enable prefixing routes directly using path identification MW * Test re-registration of routes with path ID MW * Prefix names of routes directly using path ID MW * Fix code style (php-cs-fixer) * Add Livewire v3 integration example to TSP stub * Prefix route name only if it's not prefixed already * Rename ReregisterUniversalRoutes to ReregisterRoutesAsTenant * Fix code style (php-cs-fixer) * Improve ReregisterRoutesAsTenant * Add/update TenancyUrlGenerator docblocks * Update action name in comments/test names * Update reregister action annotation * Delete unused imports * Improve comments * Make method protected * Improve TenancyUrlGenerator code * Test bypass parameter removal * Fix comment * Update annotation * Improve shouldReregisterRoute * Fix typo, delete redundant comment * Improve skipRoute * Improve shouldBeSkipped * Add and test `$passTenantParameterToRoutes` * add a comment * Fix typo in comment * Pass array as $parameters in prepareRouteInputs * Make path_identification_middleware an array * Fix code style (php-cs-fixer) * Fix ReregisterRouteAsTenant * Move tenantParameterName and tenantRouteNamePrefix getting to PathIdentificationManager * Make PathIdentificationManager properties `Closure|null` * Fix code style (php-cs-fixer) * Fix PathIdentificationManager * Update comments * Use foreach for dataset definition * Extract repetitive inGlobalStack and routeHasMiddleware calls * Refactor PathIdentificationManager * Update TenancyUrlGenerator annotation * Add $skippedRoutes, refactor ReregisterRoutesAsTenant * Improve reregisterRoute * Update re-register action annotation * update test name * Make PathIdentificationManager methods static again, update comments * Add test comment * Update ForgetTenantParameter annotation * Improve route re-registration condition, add comment * Change "re-register" to "clone" * minor code improvements --------- Co-authored-by: lukinovec <lukinovec@gmail.com> Co-authored-by: Samuel Štancl <samuel.stancl@gmail.com> Co-authored-by: PHP CS Fixer <phpcsfixer@example.com>
This commit is contained in:
parent
bd9bbe8b41
commit
1d0ca27bc8
53 changed files with 2668 additions and 271 deletions
171
src/Actions/CloneRoutesAsTenant.php
Normal file
171
src/Actions/CloneRoutesAsTenant.php
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Actions;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Config\Repository;
|
||||
use Illuminate\Routing\Route;
|
||||
use Illuminate\Routing\Router;
|
||||
use Illuminate\Support\Collection;
|
||||
use Stancl\Tenancy\PathIdentificationManager;
|
||||
use Stancl\Tenancy\RouteMode;
|
||||
|
||||
/**
|
||||
* The CloneRoutesAsTenant action clones
|
||||
* routes flagged with the 'universal' middleware,
|
||||
* all routes without a flag if the default route mode is universal,
|
||||
* and routes that directly use the InitializeTenancyByPath middleware.
|
||||
*
|
||||
* The main purpose of this action is to make the integration
|
||||
* of packages (e.g., Jetstream or Livewire) easier with path-based tenant identification.
|
||||
*
|
||||
* By default, universal routes are cloned as tenant routes (= they get flagged with the 'tenant' middleware)
|
||||
* and prefixed with the '/{tenant}' path prefix. Their name also gets prefixed with the tenant name prefix.
|
||||
*
|
||||
* Routes with the path identification middleware get cloned similarly, but only if they're not universal at the same time.
|
||||
* Unlike universal routes, these routes don't get the tenant flag,
|
||||
* because they don't need it (they're not universal, and they have the identification MW, so they're already considered tenant).
|
||||
*
|
||||
* You can use the `cloneUsing()` hook to customize the route definitions,
|
||||
* and the `skipRoute()` method to skip cloning of specific routes.
|
||||
* You can also use the $tenantParameterName and $tenantRouteNamePrefix
|
||||
* static properties to customize the tenant parameter name or the route name prefix.
|
||||
*
|
||||
* Note that routes already containing the tenant parameter or prefix won't be cloned.
|
||||
*/
|
||||
class CloneRoutesAsTenant
|
||||
{
|
||||
protected array $cloneRouteUsing = [];
|
||||
protected array $skippedRoutes = [];
|
||||
|
||||
public function __construct(
|
||||
protected Router $router,
|
||||
protected Repository $config,
|
||||
) {
|
||||
}
|
||||
|
||||
public function handle(): void
|
||||
{
|
||||
$tenantParameterName = PathIdentificationManager::getTenantParameterName();
|
||||
$routePrefix = '/{' . $tenantParameterName . '}';
|
||||
|
||||
/** @var Collection<Route> $routesToClone Only clone non-skipped routes without the tenant parameter. */
|
||||
$routesToClone = collect($this->router->getRoutes()->get())->filter(function (Route $route) use ($tenantParameterName) {
|
||||
return ! (in_array($tenantParameterName, $route->parameterNames()) || in_array($route->getName(), $this->skippedRoutes));
|
||||
});
|
||||
|
||||
if ($this->config->get('tenancy.default_route_mode') !== RouteMode::UNIVERSAL) {
|
||||
// Only clone routes with route-level path identification and universal routes
|
||||
$routesToClone = $routesToClone->where(function (Route $route) {
|
||||
$routeIsUniversal = tenancy()->routeHasMiddleware($route, 'universal');
|
||||
|
||||
return PathIdentificationManager::pathIdentificationOnRoute($route) || $routeIsUniversal;
|
||||
});
|
||||
}
|
||||
|
||||
$this->router->prefix($routePrefix)->group(fn () => $routesToClone->each(fn (Route $route) => $this->cloneRoute($route)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Make the action clone a specific route using the provided callback instead of the default one.
|
||||
*/
|
||||
public function cloneUsing(string $routeName, Closure $callback): static
|
||||
{
|
||||
$this->cloneRouteUsing[$routeName] = $callback;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Skip a route's cloning.
|
||||
*/
|
||||
public function skipRoute(string $routeName): static
|
||||
{
|
||||
$this->skippedRoutes[] = $routeName;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clone a route using a callback specified in the $cloneRouteUsing property (using the cloneUsing method).
|
||||
* If there's no callback specified for the route, use the default way of cloning routes.
|
||||
*/
|
||||
protected function cloneRoute(Route $route): void
|
||||
{
|
||||
$routeName = $route->getName();
|
||||
|
||||
// If the route's cloning callback exists
|
||||
// Use the callback to clone the route instead of the default way of cloning routes
|
||||
if ($routeName && $customRouteCallback = data_get($this->cloneRouteUsing, $routeName)) {
|
||||
$customRouteCallback($route);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$routesAreUniversalByDefault = $this->config->get('tenancy.default_route_mode') === RouteMode::UNIVERSAL;
|
||||
$routeHasIdentificationMiddleware = tenancy()->routeHasIdentificationMiddleware($route);
|
||||
$routeHasPathIdentification = PathIdentificationManager::pathIdentificationOnRoute($route);
|
||||
$pathIdentificationMiddlewareInGlobalStack = PathIdentificationManager::pathIdentificationInGlobalStack();
|
||||
|
||||
// Determine if the passed route should get cloned
|
||||
// The route should be cloned if it has path identification middleware
|
||||
// Or if the route doesn't have identification middleware and path identification middleware
|
||||
// Is not used globally or the routes are universal by default
|
||||
$shouldCloneRoute = $routeHasPathIdentification ||
|
||||
(! $routeHasIdentificationMiddleware && ($routesAreUniversalByDefault || $pathIdentificationMiddlewareInGlobalStack));
|
||||
|
||||
if ($shouldCloneRoute) {
|
||||
$newRoute = $this->createNewRoute($route);
|
||||
$routeIsUniversal = tenancy()->routeHasMiddleware($newRoute, 'universal');
|
||||
|
||||
// Add the 'tenant' flag to the new route if the route is universal
|
||||
// Or if it isn't universal and it doesn't have the identification middlware (= it isn't "flagged" as tenant by having the MW)
|
||||
if ((! $routeHasPathIdentification && ! $routeIsUniversal) || $routeIsUniversal || $routesAreUniversalByDefault) {
|
||||
$newRoute->middleware('tenant');
|
||||
}
|
||||
|
||||
$this->copyMiscRouteProperties($route, $newRoute);
|
||||
}
|
||||
}
|
||||
|
||||
protected function createNewRoute(Route $route): Route
|
||||
{
|
||||
$method = strtolower($route->methods()[0]);
|
||||
$routeName = $route->getName();
|
||||
$tenantRouteNamePrefix = PathIdentificationManager::getTenantRouteNamePrefix();
|
||||
|
||||
/** @var Route $newRoute */
|
||||
$newRoute = $this->router->$method($route->uri(), $route->action);
|
||||
|
||||
// Delete middleware from the new route and
|
||||
// Add original route middleware to ensure there's no duplicate middleware
|
||||
unset($newRoute->action['middleware']);
|
||||
|
||||
$newRoute->middleware(tenancy()->getRouteMiddleware($route));
|
||||
|
||||
if ($routeName && ! $route->named($tenantRouteNamePrefix . '*')) {
|
||||
// Clear the route name so that `name()` sets the route name instead of suffixing it
|
||||
unset($newRoute->action['as']);
|
||||
|
||||
$newRoute->name($tenantRouteNamePrefix . $routeName);
|
||||
}
|
||||
|
||||
return $newRoute;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy misc properties of the original route to the new route.
|
||||
*/
|
||||
protected function copyMiscRouteProperties(Route $originalRoute, Route $newRoute): void
|
||||
{
|
||||
$newRoute
|
||||
->setBindingFields($originalRoute->bindingFields())
|
||||
->setFallback($originalRoute->isFallback)
|
||||
->setWheres($originalRoute->wheres)
|
||||
->block($originalRoute->locksFor(), $originalRoute->waitsFor())
|
||||
->withTrashed($originalRoute->allowsTrashedBindings())
|
||||
->setDefaults($originalRoute->defaults);
|
||||
}
|
||||
}
|
||||
|
|
@ -16,19 +16,19 @@ class CreateStorageSymlinksAction
|
|||
{
|
||||
use DealsWithTenantSymlinks;
|
||||
|
||||
public static function handle(Tenant|Collection|LazyCollection $tenants, bool $relativeLink = false, bool $force = false): void
|
||||
public function __invoke(Tenant|Collection|LazyCollection $tenants, bool $relativeLink = false, bool $force = false): void
|
||||
{
|
||||
$tenants = $tenants instanceof Tenant ? collect([$tenants]) : $tenants;
|
||||
|
||||
/** @var Tenant $tenant */
|
||||
foreach ($tenants as $tenant) {
|
||||
foreach (static::possibleTenantSymlinks($tenant) as $publicPath => $storagePath) {
|
||||
static::createLink($publicPath, $storagePath, $tenant, $relativeLink, $force);
|
||||
foreach ($this->possibleTenantSymlinks($tenant) as $publicPath => $storagePath) {
|
||||
$this->createLink($publicPath, $storagePath, $tenant, $relativeLink, $force);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected static function createLink(string $publicPath, string $storagePath, Tenant $tenant, bool $relativeLink, bool $force): void
|
||||
protected function createLink(string $publicPath, string $storagePath, Tenant $tenant, bool $relativeLink, bool $force): void
|
||||
{
|
||||
event(new CreatingStorageSymlink($tenant));
|
||||
|
||||
|
|
|
|||
|
|
@ -15,21 +15,21 @@ class RemoveStorageSymlinksAction
|
|||
{
|
||||
use DealsWithTenantSymlinks;
|
||||
|
||||
public static function handle(Tenant|Collection|LazyCollection $tenants): void
|
||||
public function __invoke(Tenant|Collection|LazyCollection $tenants): void
|
||||
{
|
||||
$tenants = $tenants instanceof Tenant ? collect([$tenants]) : $tenants;
|
||||
|
||||
/** @var Tenant $tenant */
|
||||
foreach ($tenants as $tenant) {
|
||||
foreach (static::possibleTenantSymlinks($tenant) as $publicPath => $storagePath) {
|
||||
static::removeLink($publicPath, $tenant);
|
||||
foreach ($this->possibleTenantSymlinks($tenant) as $publicPath => $storagePath) {
|
||||
$this->removeLink($publicPath, $tenant);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected static function removeLink(string $publicPath, Tenant $tenant): void
|
||||
protected function removeLink(string $publicPath, Tenant $tenant): void
|
||||
{
|
||||
if (static::symlinkExists($publicPath)) {
|
||||
if ($this->symlinkExists($publicPath)) {
|
||||
event(new RemovingStorageSymlink($tenant));
|
||||
|
||||
app()->make('files')->delete($publicPath);
|
||||
|
|
|
|||
|
|
@ -0,0 +1,57 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Bootstrappers\Integrations;
|
||||
|
||||
use Illuminate\Config\Repository;
|
||||
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
|
||||
use Stancl\Tenancy\Contracts\Tenant;
|
||||
|
||||
/**
|
||||
* Allows customizing Fortify redirect URLs.
|
||||
* Intended to be used with UrlBindingBootstrapper.
|
||||
*
|
||||
* @see \Stancl\Tenancy\Bootstrappers\UrlBindingBootstrapper
|
||||
*/
|
||||
class FortifyRouteTenancyBootstrapper implements TenancyBootstrapper
|
||||
{
|
||||
// 'fortify_action' => 'tenant_route_name'
|
||||
public static array $fortifyRedirectTenantMap = [
|
||||
// 'logout' => 'welcome',
|
||||
];
|
||||
|
||||
// Fortify home route name
|
||||
public static string|null $fortifyHome = 'dashboard';
|
||||
protected array|null $originalFortifyConfig = null;
|
||||
|
||||
public function __construct(
|
||||
protected Repository $config,
|
||||
) {
|
||||
}
|
||||
|
||||
public function bootstrap(Tenant $tenant): void
|
||||
{
|
||||
$this->originalFortifyConfig = $this->config->get('fortify');
|
||||
|
||||
$this->useTenantRoutesInFortify();
|
||||
}
|
||||
|
||||
public function revert(): void
|
||||
{
|
||||
$this->config->set('fortify', $this->originalFortifyConfig);
|
||||
}
|
||||
|
||||
protected function useTenantRoutesInFortify(): void
|
||||
{
|
||||
// Regenerate the URLs after the behavior of the route() helper has been modified
|
||||
// in UrlBindingBootstrapper to generate URLs specific to the current tenant
|
||||
$tenantRoutes = array_map(fn (string $routeName) => route($routeName), static::$fortifyRedirectTenantMap);
|
||||
|
||||
if (static::$fortifyHome) {
|
||||
$this->config->set('fortify.home', route(static::$fortifyHome));
|
||||
}
|
||||
|
||||
$this->config->set('fortify.redirects', array_merge($this->config->get('fortify.redirects') ?? [], $tenantRoutes));
|
||||
}
|
||||
}
|
||||
69
src/Bootstrappers/UrlBindingBootstrapper.php
Normal file
69
src/Bootstrappers/UrlBindingBootstrapper.php
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Bootstrappers;
|
||||
|
||||
use Illuminate\Contracts\Foundation\Application;
|
||||
use Illuminate\Routing\UrlGenerator;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
|
||||
use Stancl\Tenancy\Contracts\Tenant;
|
||||
use Stancl\Tenancy\TenancyUrlGenerator;
|
||||
|
||||
/**
|
||||
* Makes the app use TenancyUrlGenerator (instead of Illuminate\Routing\UrlGenerator) which:
|
||||
* - prefixes route names with the tenant route name prefix (PathTenantResolver::tenantRouteNamePrefix() by default)
|
||||
* - passes the tenant parameter to the link generated by route() and temporarySignedRoute() (PathTenantResolver::tenantParameterName() by default).
|
||||
*
|
||||
* Used with path and query string identification.
|
||||
*
|
||||
* @see TenancyUrlGenerator
|
||||
* @see \Stancl\Tenancy\Resolvers\PathTenantResolver
|
||||
*/
|
||||
class UrlBindingBootstrapper implements TenancyBootstrapper
|
||||
{
|
||||
public function __construct(
|
||||
protected Application $app,
|
||||
protected UrlGenerator $originalUrlGenerator,
|
||||
) {
|
||||
}
|
||||
|
||||
public function bootstrap(Tenant $tenant): void
|
||||
{
|
||||
URL::clearResolvedInstances();
|
||||
|
||||
$this->useTenancyUrlGenerator();
|
||||
}
|
||||
|
||||
public function revert(): void
|
||||
{
|
||||
$this->app->bind('url', fn () => $this->originalUrlGenerator);
|
||||
}
|
||||
|
||||
/**
|
||||
* Make 'url' resolve to an instance of TenancyUrlGenerator.
|
||||
*
|
||||
* @see \Illuminate\Routing\RoutingServiceProvider registerUrlGenerator()
|
||||
*/
|
||||
protected function useTenancyUrlGenerator(): void
|
||||
{
|
||||
$this->app->extend('url', function (UrlGenerator $urlGenerator, Application $app) {
|
||||
$newGenerator = new TenancyUrlGenerator(
|
||||
$app['router']->getRoutes(),
|
||||
$urlGenerator->getRequest(),
|
||||
$app['config']->get('app.asset_url'),
|
||||
);
|
||||
|
||||
$newGenerator->setSessionResolver(function () {
|
||||
return $this->app['session'] ?? null;
|
||||
});
|
||||
|
||||
$newGenerator->setKeyResolver(function () {
|
||||
return $this->app->make('config')->get('app.key');
|
||||
});
|
||||
|
||||
return $newGenerator;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -44,14 +44,14 @@ class Link extends Command
|
|||
|
||||
protected function removeLinks(LazyCollection $tenants): void
|
||||
{
|
||||
RemoveStorageSymlinksAction::handle($tenants);
|
||||
(new RemoveStorageSymlinksAction)($tenants);
|
||||
|
||||
$this->components->info('The links have been removed.');
|
||||
}
|
||||
|
||||
protected function createLinks(LazyCollection $tenants): void
|
||||
{
|
||||
CreateStorageSymlinksAction::handle(
|
||||
(new CreateStorageSymlinksAction)(
|
||||
$tenants,
|
||||
(bool) ($this->option('relative') ?? false),
|
||||
(bool) ($this->option('force') ?? false),
|
||||
|
|
|
|||
144
src/Concerns/DealsWithEarlyIdentification.php
Normal file
144
src/Concerns/DealsWithEarlyIdentification.php
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Concerns;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Route;
|
||||
use Illuminate\Routing\Router;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\Route as RouteFacade;
|
||||
use Stancl\Tenancy\Context;
|
||||
use Stancl\Tenancy\RouteMode;
|
||||
|
||||
// todo1 Name – maybe DealsWithMiddlewareContexts?
|
||||
trait DealsWithEarlyIdentification
|
||||
{
|
||||
/**
|
||||
* Get route's middleware context (tenant or central).
|
||||
* The context is determined by the route's middleware.
|
||||
*
|
||||
* If the route has the 'central' middleware, the context is central.
|
||||
* If the route has the 'tenant' middleware, or any tenancy identification middleware, the context is tenant.
|
||||
*
|
||||
* If the route doesn't have any of the mentioned middleware,
|
||||
* the context is determined by the `tenancy.default_route_mode` config.
|
||||
*/
|
||||
public static function getMiddlewareContext(Route $route): RouteMode
|
||||
{
|
||||
if (static::routeHasMiddleware($route, 'central')) {
|
||||
return RouteMode::CENTRAL;
|
||||
}
|
||||
|
||||
$defaultRouteMode = config('tenancy.default_route_mode');
|
||||
$routeIsUniversal = $defaultRouteMode === RouteMode::UNIVERSAL || static::routeHasMiddleware($route, 'universal');
|
||||
|
||||
// If a route has identification middleware AND the route isn't universal, don't consider the context tenant
|
||||
if (static::routeHasMiddleware($route, 'tenant') || static::routeHasIdentificationMiddleware($route) && ! $routeIsUniversal) {
|
||||
return RouteMode::TENANT;
|
||||
}
|
||||
|
||||
return $defaultRouteMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get middleware of the passed route (without controller middleware and middleware from the global stack).
|
||||
*
|
||||
* First, get the surface-level route middleware (`$route->middleware()`).
|
||||
* The surface-level middleware could contain middleware groups,
|
||||
* and to accurately get all the specific middleware, we need to unpack them.
|
||||
* The unpacked middleware groups could also have middleware groups inside them,
|
||||
* so we further unpack these, three times.
|
||||
*
|
||||
* For example, a route has a 'surface' middleware group.
|
||||
* The 'surface' group has a 'first-level' group, and that group has a 'second-level' group (three middleware group layers).
|
||||
* The 'second-level' group has a specific middleware (e.g. SomeMiddleware).
|
||||
* Using the getRouteMiddleware method on that route will get you all the middleware the route has, including SomeMiddleware.
|
||||
*
|
||||
* Note that the unpacking doesn't go further than three layers – if 'second-level' had 'third-level' that would have ThirdLevelMiddleware,
|
||||
* the middleware returned by this method won't include ThirdLevelMiddleware because the 'third-level' group won't get unpacked.
|
||||
*/
|
||||
public static function getRouteMiddleware(Route $route): array
|
||||
{
|
||||
$routeMiddleware = $route->middleware();
|
||||
$middlewareGroups = RouteFacade::getMiddlewareGroups();
|
||||
$unpackGroupMiddleware = function (array $middleware) use ($middlewareGroups) {
|
||||
$innerMiddleware = [];
|
||||
|
||||
foreach ($middleware as $inner) {
|
||||
if (! $inner instanceof Closure && isset($middlewareGroups[$inner])) {
|
||||
$innerMiddleware = Arr::wrap($middlewareGroups[$inner]);
|
||||
}
|
||||
}
|
||||
|
||||
return $innerMiddleware;
|
||||
};
|
||||
|
||||
return array_unique(array_merge(
|
||||
$routeMiddleware,
|
||||
$firstLevelUnpackedGroupMiddleware = $unpackGroupMiddleware($routeMiddleware),
|
||||
$thirdLevelUnpackedGroupMiddleware = $unpackGroupMiddleware($firstLevelUnpackedGroupMiddleware),
|
||||
$unpackGroupMiddleware($thirdLevelUnpackedGroupMiddleware)
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the passed route has the passed middleware
|
||||
* three layers deep – explained in the annotation of getRouteMiddleware().
|
||||
*/
|
||||
public static function routeHasMiddleware(Route $route, string $middleware): bool
|
||||
{
|
||||
return in_array($middleware, static::getRouteMiddleware($route));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a route has identification middleware.
|
||||
*/
|
||||
public static function routeHasIdentificationMiddleware(Route $route): bool
|
||||
{
|
||||
foreach (static::getRouteMiddleware($route) as $middleware) {
|
||||
if (in_array($middleware, static::middleware())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a route uses domain identification.
|
||||
*/
|
||||
public static function routeHasDomainIdentificationMiddleware(Route $route): bool
|
||||
{
|
||||
$routeMiddleware = static::getRouteMiddleware($route);
|
||||
|
||||
foreach (config('tenancy.identification.domain_identification_middleware') as $middleware) {
|
||||
if (in_array($middleware, $routeMiddleware)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtain route from the passed request.
|
||||
* If the route isn't directly available on the request,
|
||||
* find the route that matches the passed request.
|
||||
*/
|
||||
public function getRoute(Request $request): Route
|
||||
{
|
||||
/** @var ?Route $route */
|
||||
$route = $request->route();
|
||||
|
||||
if (! $route) {
|
||||
/** @var Router $router */
|
||||
$router = app(Router::class);
|
||||
$route = $router->getRoutes()->match($request);
|
||||
}
|
||||
|
||||
return $route;
|
||||
}
|
||||
}
|
||||
|
|
@ -18,7 +18,7 @@ trait DealsWithTenantSymlinks
|
|||
*
|
||||
* @return Collection<string, string>
|
||||
*/
|
||||
protected static function possibleTenantSymlinks(Tenant $tenant): Collection
|
||||
protected function possibleTenantSymlinks(Tenant $tenant): Collection
|
||||
{
|
||||
$diskUrls = config('tenancy.filesystem.url_override');
|
||||
$disks = config('tenancy.filesystem.root_override');
|
||||
|
|
@ -41,7 +41,7 @@ trait DealsWithTenantSymlinks
|
|||
}
|
||||
|
||||
/** Determine if the provided path is an existing symlink. */
|
||||
protected static function symlinkExists(string $link): bool
|
||||
protected function symlinkExists(string $link): bool
|
||||
{
|
||||
return file_exists($link) && is_link($link);
|
||||
}
|
||||
|
|
|
|||
118
src/Concerns/UsableWithEarlyIdentification.php
Normal file
118
src/Concerns/UsableWithEarlyIdentification.php
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Concerns;
|
||||
|
||||
use Illuminate\Contracts\Http\Kernel;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Route;
|
||||
use Stancl\Tenancy\Context;
|
||||
use Stancl\Tenancy\Exceptions\MiddlewareNotUsableWithUniversalRoutesException;
|
||||
use Stancl\Tenancy\Middleware\IdentificationMiddleware;
|
||||
use Stancl\Tenancy\Middleware\PreventAccessFromUnwantedDomains;
|
||||
use Stancl\Tenancy\RouteMode;
|
||||
|
||||
/**
|
||||
* This trait provides methods that check if a middleware's execution should be skipped.
|
||||
* This is primarily used to ensure that kernel identification is skipped when the route has
|
||||
* identification middleware (= route-level identification is prioritized over kernel identification).
|
||||
*
|
||||
* When using kernel domain identification, you'll most likely also use the PreventAccessFromUnwantedDomains middleware in the global stack.
|
||||
* PreventAccessFromUnwantedDomains isn't an identification middleware, but we have to skip it too,
|
||||
* e.g. when using the MW in the global stack and at the same time, we're using route-level identification.
|
||||
*
|
||||
* You need to use this trait directly on each identification middleware — it can't be used in a base class that's extended.
|
||||
* The inGlobalStack() method checks for the specific middleware the trait is used on (`static::class`).
|
||||
*/
|
||||
trait UsableWithEarlyIdentification
|
||||
{
|
||||
/**
|
||||
* Skip middleware if the route is universal and uses path identification or if the route is universal and the context should be central.
|
||||
* Universal routes using path identification should get re-registered using ReregisterRoutesAsTenant.
|
||||
*
|
||||
* @see \Stancl\Tenancy\Actions\CloneRoutesAsTenant
|
||||
*/
|
||||
protected function shouldBeSkipped(Route $route): bool
|
||||
{
|
||||
$routeMiddleware = tenancy()->getRouteMiddleware($route);
|
||||
$universalFlagUsed = in_array('universal', $routeMiddleware);
|
||||
$defaultToUniversalRoutes = config('tenancy.default_route_mode') === RouteMode::UNIVERSAL;
|
||||
|
||||
// Route is universal only if it doesn't have the central/tenant flag
|
||||
$routeIsUniversal = ($universalFlagUsed || $defaultToUniversalRoutes) &&
|
||||
! (in_array('central', $routeMiddleware) || in_array('tenant', $routeMiddleware));
|
||||
|
||||
if ($routeIsUniversal && $this instanceof IdentificationMiddleware) {
|
||||
/** @phpstan-ignore-next-line */
|
||||
throw_unless($this instanceof UsableWithUniversalRoutes, MiddlewareNotUsableWithUniversalRoutesException::class);
|
||||
|
||||
return $this->determineUniversalRouteContextFromRequest(request()) === Context::CENTRAL;
|
||||
}
|
||||
|
||||
// If the middleware is not in the global stack (= it's used directly on the route)
|
||||
// And the route isn't universal, don't skip it
|
||||
if (! static::inGlobalStack()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Now that we're sure the MW isn't used in the global MW stack, we determine whether to skip it
|
||||
if ($this instanceof PreventAccessFromUnwantedDomains) {
|
||||
// Skip access prevention if the route directly uses a non-domain identification middleware
|
||||
return tenancy()->routeHasIdentificationMiddleware($route) && ! tenancy()->routeHasDomainIdentificationMiddleware($route);
|
||||
}
|
||||
|
||||
return $this->shouldIdentificationMiddlewareBeSkipped($route);
|
||||
}
|
||||
|
||||
protected function determineUniversalRouteContextFromRequest(Request $request): Context
|
||||
{
|
||||
$route = tenancy()->getRoute($request);
|
||||
|
||||
// Check if this is the identification middleware the route should be using
|
||||
// Route-level identification middleware is prioritized
|
||||
$middlewareUsed = tenancy()->routeHasMiddleware($route, static::class) || ! tenancy()->routeHasIdentificationMiddleware($route) && static::inGlobalStack();
|
||||
|
||||
/** @var UsableWithUniversalRoutes $this */
|
||||
return $middlewareUsed && $this->requestHasTenant($request) ? Context::TENANT : Context::CENTRAL;
|
||||
}
|
||||
|
||||
protected function shouldIdentificationMiddlewareBeSkipped(Route $route): bool
|
||||
{
|
||||
if (! static::inGlobalStack()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$request = app(Request::class);
|
||||
|
||||
if (! $request->attributes->get('_tenancy_kernel_identification_skipped')) {
|
||||
if (
|
||||
// Skip identification if the current route is central
|
||||
// The route is central if defaulting is set to central and the route isn't flagged as tenant or it doesn't have identification middleware
|
||||
tenancy()->getMiddlewareContext($route) === RouteMode::CENTRAL
|
||||
// Don't skip identification if the central route is considered universal
|
||||
&& (config('tenancy.default_route_mode') !== RouteMode::UNIVERSAL || ! tenancy()->routeHasMiddleware($route, 'universal'))
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Skip kernel identification if the route uses route-level identification
|
||||
if (tenancy()->routeHasIdentificationMiddleware($route)) {
|
||||
// Remember that it was attempted to identify a tenant using kernel identification
|
||||
// By making the $kernelIdentificationSkipped property of the current Tenancy instance true
|
||||
// So that the next identification middleware gets executed (= route-level identification MW doesn't get skipped)
|
||||
$request->attributes->set('_tenancy_kernel_identification_skipped', true);
|
||||
|
||||
// Skip kernel identification so that route-level identification middleware can get used
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static function inGlobalStack(): bool
|
||||
{
|
||||
return app(Kernel::class)->hasMiddleware(static::class);
|
||||
}
|
||||
}
|
||||
26
src/Concerns/UsableWithUniversalRoutes.php
Normal file
26
src/Concerns/UsableWithUniversalRoutes.php
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Concerns;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* Identification middleware has to implement this in order to make universal routes work with it,.
|
||||
*/
|
||||
interface UsableWithUniversalRoutes
|
||||
{
|
||||
/**
|
||||
* Determine if the tenant is present in the incoming request.
|
||||
*
|
||||
* Because universal routes can be in any context (central/tenant),
|
||||
* we use this to determine the context. We can't just check for
|
||||
* the route's middleware to determine the route's context.
|
||||
*
|
||||
* For example, route '/foo' has the 'universal' and InitializeTenancyByRequestData middleware.
|
||||
* When visiting the route, we should determine the context by the presence of the tenant payload.
|
||||
* The context is tenant if the tenant parameter is present (e.g. '?tenant=foo'), otherwise the context is central.
|
||||
*/
|
||||
public function requestHasTenant(Request $request): bool;
|
||||
}
|
||||
11
src/Context.php
Normal file
11
src/Context.php
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy;
|
||||
|
||||
enum Context
|
||||
{
|
||||
case TENANT;
|
||||
case CENTRAL;
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Exceptions;
|
||||
|
||||
use Exception;
|
||||
|
||||
class MiddlewareNotUsableWithUniversalRoutesException extends Exception
|
||||
{
|
||||
public function __construct(string $message = '')
|
||||
{
|
||||
parent::__construct($message ?: 'Universal routes are usable only with identification middleware that implements UsableWithUniversalRoutes.');
|
||||
}
|
||||
}
|
||||
|
|
@ -23,6 +23,6 @@ class CreateStorageSymlinks implements ShouldQueue
|
|||
|
||||
public function handle(): void
|
||||
{
|
||||
CreateStorageSymlinksAction::handle($this->tenant);
|
||||
(new CreateStorageSymlinksAction)($this->tenant);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -35,6 +35,6 @@ class RemoveStorageSymlinks implements ShouldQueue
|
|||
*/
|
||||
public function handle()
|
||||
{
|
||||
RemoveStorageSymlinksAction::handle($this->tenant);
|
||||
(new RemoveStorageSymlinksAction)($this->tenant);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
36
src/Listeners/ForgetTenantParameter.php
Normal file
36
src/Listeners/ForgetTenantParameter.php
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Listeners;
|
||||
|
||||
use Illuminate\Routing\Events\RouteMatched;
|
||||
use Stancl\Tenancy\PathIdentificationManager;
|
||||
use Stancl\Tenancy\RouteMode;
|
||||
|
||||
/**
|
||||
* Remove the tenant parameter from the matched route when path identification is used globally.
|
||||
*
|
||||
* The tenant parameter gets forgotten using PathTenantResolver so that the route actions don't have to accept it.
|
||||
* Then, tenancy gets initialized, and URL::defaults() is used to give the tenant parameter to the next matched route.
|
||||
* But with kernel identification, the route gets matched AFTER the point when URL::defaults() is used,
|
||||
* and because of that, the matched route gets the tenant parameter again, so we forget the parameter again on RouteMatched.
|
||||
*
|
||||
* We remove the {tenant} parameter from the hydrated route when
|
||||
* 1) the InitializeTenancyByPath middleware is in the global stack, AND
|
||||
* 2) the matched route does not have identification middleware (so that {tenant} isn't forgotten when using route-level identification), AND
|
||||
* 3) the route has tenant middleware context (so that {tenant} doesn't get accidentally removed from central routes).
|
||||
*/
|
||||
class ForgetTenantParameter
|
||||
{
|
||||
public function handle(RouteMatched $event): void
|
||||
{
|
||||
if (
|
||||
PathIdentificationManager::pathIdentificationInGlobalStack() &&
|
||||
! tenancy()->routeHasIdentificationMiddleware($event->route) &&
|
||||
tenancy()->getMiddlewareContext($event->route) === RouteMode::TENANT
|
||||
) {
|
||||
$event->route->forgetParameter(PathIdentificationManager::getTenantParameterName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -6,11 +6,15 @@ namespace Stancl\Tenancy\Middleware;
|
|||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Stancl\Tenancy\Concerns\UsableWithEarlyIdentification;
|
||||
use Stancl\Tenancy\Concerns\UsableWithUniversalRoutes;
|
||||
use Stancl\Tenancy\Resolvers\DomainTenantResolver;
|
||||
use Stancl\Tenancy\Tenancy;
|
||||
|
||||
class InitializeTenancyByDomain extends IdentificationMiddleware
|
||||
class InitializeTenancyByDomain extends IdentificationMiddleware implements UsableWithUniversalRoutes
|
||||
{
|
||||
use UsableWithEarlyIdentification;
|
||||
|
||||
public static ?Closure $onFail = null;
|
||||
|
||||
public function __construct(
|
||||
|
|
@ -22,6 +26,11 @@ class InitializeTenancyByDomain extends IdentificationMiddleware
|
|||
/** @return \Illuminate\Http\Response|mixed */
|
||||
public function handle(Request $request, Closure $next): mixed
|
||||
{
|
||||
if ($this->shouldBeSkipped(tenancy()->getRoute($request))) {
|
||||
// Allow accessing central route in kernel identification
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
if (in_array($request->getHost(), config('tenancy.central_domains', []), true)) {
|
||||
// Always bypass tenancy initialization when host is in central domains
|
||||
return $next($request);
|
||||
|
|
@ -33,4 +42,13 @@ class InitializeTenancyByDomain extends IdentificationMiddleware
|
|||
$request->getHost()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Domain identification request has a tenant if it's
|
||||
* not hitting a domain specifically defined as central in the config.
|
||||
*/
|
||||
public function requestHasTenant(Request $request): bool
|
||||
{
|
||||
return ! in_array($request->host(), config('tenancy.central_domains'));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,19 +5,52 @@ declare(strict_types=1);
|
|||
namespace Stancl\Tenancy\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Exception;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Str;
|
||||
use Stancl\Tenancy\Concerns\UsableWithEarlyIdentification;
|
||||
|
||||
class InitializeTenancyByDomainOrSubdomain
|
||||
class InitializeTenancyByDomainOrSubdomain extends InitializeTenancyBySubdomain
|
||||
{
|
||||
use UsableWithEarlyIdentification;
|
||||
|
||||
/** @return \Illuminate\Http\Response|mixed */
|
||||
public function handle(Request $request, Closure $next): mixed
|
||||
{
|
||||
if ($this->isSubdomain($request->getHost())) {
|
||||
return app(InitializeTenancyBySubdomain::class)->handle($request, $next);
|
||||
} else {
|
||||
return app(InitializeTenancyByDomain::class)->handle($request, $next);
|
||||
if ($this->shouldBeSkipped(tenancy()->getRoute($request))) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
if (in_array($request->getHost(), config('tenancy.central_domains', []), true)) {
|
||||
// Always bypass tenancy initialization when host is in central domains
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
$domain = $request->getHost();
|
||||
|
||||
if ($this->isSubdomain($domain)) {
|
||||
$domain = $this->makeSubdomain($domain);
|
||||
|
||||
if (is_object($domain) && $domain instanceof Exception) {
|
||||
$onFail = static::$onFail ?? function ($e) {
|
||||
throw $e;
|
||||
};
|
||||
|
||||
return $onFail($domain, $request, $next);
|
||||
}
|
||||
|
||||
// If a Response instance was returned, we return it immediately.
|
||||
if (is_object($domain) && $domain instanceof Response) {
|
||||
return $domain;
|
||||
}
|
||||
}
|
||||
|
||||
return $this->initializeTenancy(
|
||||
$request,
|
||||
$next,
|
||||
$domain
|
||||
);
|
||||
}
|
||||
|
||||
protected function isSubdomain(string $hostname): bool
|
||||
|
|
|
|||
|
|
@ -6,17 +6,25 @@ namespace Stancl\Tenancy\Middleware;
|
|||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Route;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
use Stancl\Tenancy\Concerns\UsableWithEarlyIdentification;
|
||||
use Stancl\Tenancy\Concerns\UsableWithUniversalRoutes;
|
||||
use Stancl\Tenancy\Contracts\Tenant;
|
||||
use Stancl\Tenancy\Events\InitializingTenancy;
|
||||
use Stancl\Tenancy\Exceptions\RouteIsMissingTenantParameterException;
|
||||
use Stancl\Tenancy\Resolvers\PathTenantResolver;
|
||||
use Stancl\Tenancy\RouteMode;
|
||||
use Stancl\Tenancy\Tenancy;
|
||||
use Stancl\Tenancy\TenancyUrlGenerator;
|
||||
|
||||
class InitializeTenancyByPath extends IdentificationMiddleware
|
||||
/**
|
||||
* @see Stancl\Tenancy\Listeners\ForgetTenantParameter
|
||||
*/
|
||||
class InitializeTenancyByPath extends IdentificationMiddleware implements UsableWithUniversalRoutes
|
||||
{
|
||||
use UsableWithEarlyIdentification;
|
||||
|
||||
public static ?Closure $onFail = null;
|
||||
|
||||
public function __construct(
|
||||
|
|
@ -28,12 +36,19 @@ class InitializeTenancyByPath extends IdentificationMiddleware
|
|||
/** @return \Illuminate\Http\Response|mixed */
|
||||
public function handle(Request $request, Closure $next): mixed
|
||||
{
|
||||
$route = $this->route($request);
|
||||
$route = tenancy()->getRoute($request);
|
||||
|
||||
// Only initialize tenancy if tenant is the first parameter
|
||||
if ($this->shouldBeSkipped($route)) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
// Used with *route-level* identification, takes precedence over what may have been configured for global stack middleware
|
||||
TenancyUrlGenerator::$prefixRouteNames = true;
|
||||
|
||||
// Only initialize tenancy if the route has the tenant parameter.
|
||||
// We don't want to initialize tenancy if the tenant is
|
||||
// simply injected into some route controller action.
|
||||
if ($route->parameterNames()[0] === PathTenantResolver::tenantParameterName()) {
|
||||
if (in_array(PathTenantResolver::tenantParameterName(), $route->parameterNames())) {
|
||||
$this->setDefaultTenantForRouteParametersWhenInitializingTenancy();
|
||||
|
||||
return $this->initializeTenancy(
|
||||
|
|
@ -46,25 +61,6 @@ class InitializeTenancyByPath extends IdentificationMiddleware
|
|||
}
|
||||
}
|
||||
|
||||
protected function route(Request $request): Route
|
||||
{
|
||||
/** @var ?Route $route */
|
||||
$route = $request->route();
|
||||
|
||||
if (! $route) {
|
||||
// Create a fake $route instance that has enough information for this middleware's needs
|
||||
$route = new Route($request->method(), $request->getUri(), []);
|
||||
/**
|
||||
* getPathInfo() returns the path except the root domain.
|
||||
* We fetch the first parameter because tenant parameter is *always* first.
|
||||
*/
|
||||
$route->parameters[PathTenantResolver::tenantParameterName()] = explode('/', ltrim($request->getPathInfo(), '/'))[0];
|
||||
$route->parameterNames[] = PathTenantResolver::tenantParameterName();
|
||||
}
|
||||
|
||||
return $route;
|
||||
}
|
||||
|
||||
protected function setDefaultTenantForRouteParametersWhenInitializingTenancy(): void
|
||||
{
|
||||
Event::listen(InitializingTenancy::class, function (InitializingTenancy $event) {
|
||||
|
|
@ -76,4 +72,19 @@ class InitializeTenancyByPath extends IdentificationMiddleware
|
|||
]);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Path identification request has a tenant if the middleware context is tenant.
|
||||
*
|
||||
* With path identification, we can just check the MW context because we're re-registering the universal routes,
|
||||
* and the routes are flagged with the 'tenant' MW group (= their MW context is tenant).
|
||||
*
|
||||
* With other identification middleware, we have to determine the context differently because we only have one
|
||||
* truly universal route available ('truly universal' because with path identification, applying 'universal' to a route just means that
|
||||
* it should get re-registered, whereas with other ID MW, it means that the route you apply the 'universal' flag to will be accessible in both contexts).
|
||||
*/
|
||||
public function requestHasTenant(Request $request): bool
|
||||
{
|
||||
return tenancy()->getMiddlewareContext(tenancy()->getRoute($request)) === RouteMode::TENANT;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,11 +6,17 @@ namespace Stancl\Tenancy\Middleware;
|
|||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Stancl\Tenancy\Concerns\UsableWithEarlyIdentification;
|
||||
use Stancl\Tenancy\Concerns\UsableWithUniversalRoutes;
|
||||
use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedByRequestDataException;
|
||||
use Stancl\Tenancy\Resolvers\RequestDataTenantResolver;
|
||||
use Stancl\Tenancy\Tenancy;
|
||||
use Stancl\Tenancy\TenancyUrlGenerator;
|
||||
|
||||
class InitializeTenancyByRequestData extends IdentificationMiddleware
|
||||
class InitializeTenancyByRequestData extends IdentificationMiddleware implements UsableWithUniversalRoutes
|
||||
{
|
||||
use UsableWithEarlyIdentification;
|
||||
|
||||
public static string $header = 'X-Tenant';
|
||||
public static string $cookie = 'X-Tenant';
|
||||
public static string $queryParameter = 'tenant';
|
||||
|
|
@ -25,6 +31,14 @@ class InitializeTenancyByRequestData extends IdentificationMiddleware
|
|||
/** @return \Illuminate\Http\Response|mixed */
|
||||
public function handle(Request $request, Closure $next): mixed
|
||||
{
|
||||
if ($this->shouldBeSkipped(tenancy()->getRoute($request))) {
|
||||
// Allow accessing central route in kernel identification
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
// Used with *route-level* identification, takes precedence over what may have been configured for global stack middleware
|
||||
TenancyUrlGenerator::$prefixRouteNames = false;
|
||||
|
||||
if ($request->method() !== 'OPTIONS') {
|
||||
return $this->initializeTenancy($request, $next, $this->getPayload($request));
|
||||
}
|
||||
|
|
@ -32,19 +46,30 @@ class InitializeTenancyByRequestData extends IdentificationMiddleware
|
|||
return $next($request);
|
||||
}
|
||||
|
||||
protected function getPayload(Request $request): ?string
|
||||
protected function getPayload(Request $request): string|null
|
||||
{
|
||||
$payload = null;
|
||||
|
||||
if (static::$header && $request->hasHeader(static::$header)) {
|
||||
$payload = $request->header(static::$header);
|
||||
} elseif (static::$queryParameter && $request->has(static::$queryParameter)) {
|
||||
$payload = $request->get(static::$queryParameter);
|
||||
} elseif (static::$cookie && $request->hasCookie(static::$cookie)) {
|
||||
$payload = $request->cookie(static::$cookie);
|
||||
} else {
|
||||
$payload = null;
|
||||
}
|
||||
|
||||
/** @var ?string $payload */
|
||||
return $payload;
|
||||
if (is_string($payload) || is_null($payload)) {
|
||||
return $payload;
|
||||
}
|
||||
|
||||
throw new TenantCouldNotBeIdentifiedByRequestDataException($payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the request has the tenant payload.
|
||||
*/
|
||||
public function requestHasTenant(Request $request): bool
|
||||
{
|
||||
return (bool) $this->getPayload($request);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,10 +9,13 @@ use Exception;
|
|||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Str;
|
||||
use Stancl\Tenancy\Concerns\UsableWithEarlyIdentification;
|
||||
use Stancl\Tenancy\Exceptions\NotASubdomainException;
|
||||
|
||||
class InitializeTenancyBySubdomain extends InitializeTenancyByDomain
|
||||
{
|
||||
use UsableWithEarlyIdentification;
|
||||
|
||||
/**
|
||||
* The index of the subdomain fragment in the hostname
|
||||
* split by `.`. 0 for first fragment, 1 if you prefix
|
||||
|
|
@ -27,6 +30,11 @@ class InitializeTenancyBySubdomain extends InitializeTenancyByDomain
|
|||
/** @return Response|mixed */
|
||||
public function handle(Request $request, Closure $next): mixed
|
||||
{
|
||||
if ($this->shouldBeSkipped(tenancy()->getRoute($request))) {
|
||||
// Allow accessing central route in kernel identification
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
if (in_array($request->getHost(), config('tenancy.central_domains', []), true)) {
|
||||
// Always bypass tenancy initialization when host is in central domains
|
||||
return $next($request);
|
||||
|
|
|
|||
|
|
@ -7,11 +7,23 @@ namespace Stancl\Tenancy\Middleware;
|
|||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Route;
|
||||
use Illuminate\Support\Facades\Route as Router;
|
||||
use Stancl\Tenancy\Concerns\UsableWithEarlyIdentification;
|
||||
use Stancl\Tenancy\Context;
|
||||
use Stancl\Tenancy\RouteMode;
|
||||
|
||||
// todo come up with a better name
|
||||
/**
|
||||
* todo come up with a better name.
|
||||
*
|
||||
* Prevents accessing central domains in the tenant context/tenant domains in the central context.
|
||||
* The access isn't prevented if the request is trying to access a route flagged as 'universal',
|
||||
* or if this middleware should be skipped.
|
||||
*
|
||||
* @see UsableWithEarlyIdentification – more info about the skipping part
|
||||
*/
|
||||
class PreventAccessFromUnwantedDomains
|
||||
{
|
||||
use UsableWithEarlyIdentification;
|
||||
|
||||
/**
|
||||
* Set this property if you want to customize the on-fail behavior.
|
||||
*/
|
||||
|
|
@ -20,14 +32,14 @@ class PreventAccessFromUnwantedDomains
|
|||
/** @return \Illuminate\Http\Response|mixed */
|
||||
public function handle(Request $request, Closure $next): mixed
|
||||
{
|
||||
/** @var Route $route */
|
||||
$route = $request->route();
|
||||
$route = tenancy()->getRoute($request);
|
||||
$routeIsUniversal = tenancy()->routeHasMiddleware($route, 'universal') || config('tenancy.default_route_mode') === RouteMode::UNIVERSAL;
|
||||
|
||||
if ($this->routeHasMiddleware($route, 'universal')) {
|
||||
if ($this->shouldBeSkipped($route) || $routeIsUniversal) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
if (in_array($request->getHost(), config('tenancy.central_domains'), true)) {
|
||||
if ($this->accessingTenantRouteFromCentralDomain($request, $route) || $this->accessingCentralRouteFromTenantDomain($request, $route)) {
|
||||
$abortRequest = static::$abortRequest ?? function () {
|
||||
abort(404);
|
||||
};
|
||||
|
|
@ -38,24 +50,23 @@ class PreventAccessFromUnwantedDomains
|
|||
return $next($request);
|
||||
}
|
||||
|
||||
protected function routeHasMiddleware(Route $route, string $middleware): bool
|
||||
protected function accessingTenantRouteFromCentralDomain(Request $request, Route $route): bool
|
||||
{
|
||||
/** @var array $routeMiddleware */
|
||||
$routeMiddleware = $route->middleware();
|
||||
return tenancy()->getMiddlewareContext($route) === RouteMode::TENANT // Current route's middleware context is tenant
|
||||
&& $this->isCentralDomain($request); // The request comes from a domain that IS present in the configured `tenancy.central_domains`
|
||||
}
|
||||
|
||||
if (in_array($middleware, $routeMiddleware, true)) {
|
||||
return true;
|
||||
}
|
||||
protected function accessingCentralRouteFromTenantDomain(Request $request, Route $route): bool
|
||||
{
|
||||
return tenancy()->getMiddlewareContext($route) === RouteMode::CENTRAL // Current route's middleware context is central
|
||||
&& ! $this->isCentralDomain($request); // The request comes from a domain that ISN'T present in the configured `tenancy.central_domains`
|
||||
}
|
||||
|
||||
// Loop one level deep and check if the route's middleware
|
||||
// groups have the searched middleware group inside them
|
||||
$middlewareGroups = Router::getMiddlewareGroups();
|
||||
foreach ($route->gatherMiddleware() as $inner) {
|
||||
if (! $inner instanceof Closure && isset($middlewareGroups[$inner]) && in_array($middleware, $middlewareGroups[$inner], true)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
/**
|
||||
* Check if the request's host name is present in the configured `tenancy.central_domains`.
|
||||
*/
|
||||
protected function isCentralDomain(Request $request): bool
|
||||
{
|
||||
return in_array($request->getHost(), config('tenancy.central_domains'), true);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
59
src/PathIdentificationManager.php
Normal file
59
src/PathIdentificationManager.php
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Routing\Route;
|
||||
use Stancl\Tenancy\Resolvers\PathTenantResolver;
|
||||
|
||||
class PathIdentificationManager
|
||||
{
|
||||
public static Closure|null $tenantParameterName = null;
|
||||
public static Closure|null $tenantRouteNamePrefix = null;
|
||||
|
||||
/**
|
||||
* Get the tenant parameter name using the static property.
|
||||
* Default to PathTenantResolver::tenantParameterName().
|
||||
*/
|
||||
public static function getTenantParameterName(): string
|
||||
{
|
||||
return static::$tenantParameterName ? (static::$tenantParameterName)() : PathTenantResolver::tenantParameterName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the tenant route name prefix using the static property.
|
||||
* Default to PathTenantResolver::tenantRouteNamePrefix().
|
||||
*/
|
||||
public static function getTenantRouteNamePrefix(): string
|
||||
{
|
||||
return static::$tenantRouteNamePrefix ? (static::$tenantRouteNamePrefix)() : PathTenantResolver::tenantRouteNamePrefix();
|
||||
}
|
||||
|
||||
public static function pathIdentificationOnRoute(Route $route): bool
|
||||
{
|
||||
return static::checkPathIdentificationMiddleware(fn ($middleware) => tenancy()->routeHasMiddleware($route, $middleware));
|
||||
}
|
||||
|
||||
public static function pathIdentificationInGlobalStack(): bool
|
||||
{
|
||||
return static::checkPathIdentificationMiddleware(fn ($middleware) => $middleware::inGlobalStack());
|
||||
}
|
||||
|
||||
protected static function checkPathIdentificationMiddleware(Closure $closure): bool
|
||||
{
|
||||
foreach (static::getPathIdentificationMiddleware() as $middleware) {
|
||||
if ($closure($middleware)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
protected static function getPathIdentificationMiddleware(): array
|
||||
{
|
||||
return config('tenancy.identification.path_identification_middleware');
|
||||
}
|
||||
}
|
||||
|
|
@ -19,6 +19,7 @@ class PathTenantResolver extends Contracts\CachedTenantResolver
|
|||
$id = $route->parameter(static::tenantParameterName());
|
||||
|
||||
if ($id) {
|
||||
// Forget the tenant parameter so that we don't have to accept it in route action methods
|
||||
$route->forgetParameter(static::tenantParameterName());
|
||||
|
||||
if ($tenant = tenancy()->find($id)) {
|
||||
|
|
@ -40,4 +41,9 @@ class PathTenantResolver extends Contracts\CachedTenantResolver
|
|||
{
|
||||
return config('tenancy.identification.resolvers.' . static::class . '.tenant_parameter_name') ?? 'tenant';
|
||||
}
|
||||
|
||||
public static function tenantRouteNamePrefix(): string
|
||||
{
|
||||
return config('tenancy.identification.resolvers.' . static::class . '.tenant_route_name_prefix') ?? static::tenantParameterName() . '.';
|
||||
}
|
||||
}
|
||||
|
|
|
|||
12
src/RouteMode.php
Normal file
12
src/RouteMode.php
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy;
|
||||
|
||||
enum RouteMode
|
||||
{
|
||||
case TENANT;
|
||||
case CENTRAL;
|
||||
case UNIVERSAL;
|
||||
}
|
||||
|
|
@ -8,13 +8,14 @@ use Closure;
|
|||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Traits\Macroable;
|
||||
use Stancl\Tenancy\Concerns\DealsWithEarlyIdentification;
|
||||
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
|
||||
use Stancl\Tenancy\Contracts\Tenant;
|
||||
use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedByIdException;
|
||||
|
||||
class Tenancy
|
||||
{
|
||||
use Macroable;
|
||||
use Macroable, DealsWithEarlyIdentification;
|
||||
|
||||
/**
|
||||
* The current tenant.
|
||||
|
|
|
|||
|
|
@ -6,10 +6,14 @@ namespace Stancl\Tenancy;
|
|||
|
||||
use Illuminate\Cache\CacheManager;
|
||||
use Illuminate\Database\Console\Migrations\FreshCommand;
|
||||
use Illuminate\Routing\Events\RouteMatched;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Stancl\Tenancy\Bootstrappers\FilesystemTenancyBootstrapper;
|
||||
use Stancl\Tenancy\Contracts\Domain;
|
||||
use Stancl\Tenancy\Contracts\Tenant;
|
||||
use Stancl\Tenancy\Listeners\ForgetTenantParameter;
|
||||
use Stancl\Tenancy\Resolvers\DomainTenantResolver;
|
||||
|
||||
class TenancyServiceProvider extends ServiceProvider
|
||||
|
|
@ -133,5 +137,11 @@ class TenancyServiceProvider extends ServiceProvider
|
|||
|
||||
return $instance;
|
||||
});
|
||||
|
||||
Route::middlewareGroup('universal', []);
|
||||
Route::middlewareGroup('tenant', []);
|
||||
Route::middlewareGroup('central', []);
|
||||
|
||||
Event::listen(RouteMatched::class, ForgetTenantParameter::class);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
118
src/TenancyUrlGenerator.php
Normal file
118
src/TenancyUrlGenerator.php
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy; // todo new Overrides namespace?
|
||||
|
||||
use Illuminate\Routing\UrlGenerator;
|
||||
use Illuminate\Support\Arr;
|
||||
|
||||
/**
|
||||
* This class is used in place of the default UrlGenerator when UrlBindingBootstrapper is enabled.
|
||||
*
|
||||
* TenancyUrlGenerator does two extra things:
|
||||
* 1. Autofill the {tenant} parameter in the tenant context with the current tenant if $passTenantParameterToRoutes is enabled (enabled by default)
|
||||
* 2. Prepend the route name with `tenant.` (or the configured prefix) if $prefixRouteNames is enabled (disabled by default)
|
||||
*
|
||||
* Both of these can be skipped by passing the $bypassParameter (`['central' => true]` by default)
|
||||
*/
|
||||
class TenancyUrlGenerator extends UrlGenerator
|
||||
{
|
||||
/**
|
||||
* Parameter which bypasses the behavior modification of route() and temporarySignedRoute().
|
||||
*
|
||||
* E.g. route('tenant') => app.test/{tenant}/tenant (or app.test/tenant?tenant=tenantKey if the route doesn't accept the tenant parameter)
|
||||
* route('tenant', [$bypassParameter => true]) => app.test/tenant.
|
||||
*/
|
||||
public static string $bypassParameter = 'central';
|
||||
|
||||
/**
|
||||
* Determine if the route names of routes generated using
|
||||
* `route()` or `temporarySignedRoute()` should get prefixed with the tenant route name prefix.
|
||||
*
|
||||
* Set this to true when using path identification.
|
||||
*/
|
||||
public static bool $prefixRouteNames = false;
|
||||
|
||||
/**
|
||||
* Determine if the tenant parameter should get passed
|
||||
* to the links generated by `route()` or `temporarySignedRoute()`.
|
||||
*/
|
||||
public static bool $passTenantParameterToRoutes = true;
|
||||
|
||||
/**
|
||||
* Override the route() method so that the route name gets prefixed
|
||||
* and the tenant parameter gets added when in tenant context.
|
||||
*/
|
||||
public function route($name, $parameters = [], $absolute = true)
|
||||
{
|
||||
[$name, $parameters] = $this->prepareRouteInputs($name, Arr::wrap($parameters));
|
||||
|
||||
return parent::route($name, $parameters, $absolute);
|
||||
}
|
||||
|
||||
/**
|
||||
* Override the temporarySignedRoute() method so that the route name gets prefixed
|
||||
* and the tenant parameter gets added when in tenant context.
|
||||
*/
|
||||
public function temporarySignedRoute($name, $expiration, $parameters = [], $absolute = true)
|
||||
{
|
||||
[$name, $parameters] = $this->prepareRouteInputs($name, Arr::wrap($parameters));
|
||||
|
||||
return parent::temporarySignedRoute($name, $expiration, $parameters, $absolute);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return bool indicating if the bypass parameter was in $parameters.
|
||||
*/
|
||||
protected function routeBehaviorModificationBypassed(mixed $parameters): bool
|
||||
{
|
||||
if (isset($parameters[static::$bypassParameter])) {
|
||||
return (bool) $parameters[static::$bypassParameter];
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes a route name and an array of parameters to return the prefixed route name
|
||||
* and the route parameters with the tenant parameter added.
|
||||
*
|
||||
* To skip these modifications, pass the bypass parameter in route parameters.
|
||||
* Before returning the modified route inputs, the bypass parameter is removed from the parameters.
|
||||
*/
|
||||
protected function prepareRouteInputs(string $name, array $parameters): array
|
||||
{
|
||||
if (! $this->routeBehaviorModificationBypassed($parameters)) {
|
||||
$name = $this->prefixRouteName($name);
|
||||
$parameters = $this->addTenantParameter($parameters);
|
||||
}
|
||||
|
||||
// Remove bypass parameter from the route parameters
|
||||
unset($parameters[static::$bypassParameter]);
|
||||
|
||||
return [$name, $parameters];
|
||||
}
|
||||
|
||||
/**
|
||||
* If $prefixRouteNames is true, prefix the passed route name.
|
||||
*/
|
||||
protected function prefixRouteName(string $name): string
|
||||
{
|
||||
$tenantPrefix = PathIdentificationManager::getTenantRouteNamePrefix();
|
||||
|
||||
if (static::$prefixRouteNames && ! str($name)->startsWith($tenantPrefix)) {
|
||||
$name = str($name)->after($tenantPrefix)->prepend($tenantPrefix)->toString();
|
||||
}
|
||||
|
||||
return $name;
|
||||
}
|
||||
|
||||
/**
|
||||
* If `tenant()` isn't null, add tenant paramter to the passed parameters.
|
||||
*/
|
||||
protected function addTenantParameter(array $parameters): array
|
||||
{
|
||||
return tenant() && static::$passTenantParameterToRoutes ? array_merge($parameters, [PathIdentificationManager::getTenantParameterName() => tenant()->getTenantKey()]) : $parameters;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue