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

Merge dev branch (minor breaking changes)

From the perspective of the master branch, this commit merges in a
few small breaking changes from the dev branch:

6b0066c5ef
- Make pullPendingFromPool() $firstOrCreate arg default to false
  (pullPending() is now a direct alias for pullPendingFromPool() with
  default $firstOrCreate=true)
- See full commit message for other changes. They shouldn't be breaking
  though.

13a2209f11
- Remove $WAL static property. We instead just let Laravel use its
  journal_mode config now

This merge also adds a deprecation:

b320f8f33d
- Deprecate TenantConfig feature in favor of TenantConfigBootstrapper
This commit is contained in:
Samuel Štancl 2025-10-14 17:30:24 +02:00
commit 151e81b412
No known key found for this signature in database
GPG key ID: BA146259A1E16C57
43 changed files with 443 additions and 223 deletions

View file

@ -86,6 +86,7 @@ class CloneRoutesAsTenant
{
protected array $routesToClone = [];
protected bool $addTenantParameter = true;
protected bool $tenantParameterBeforePrefix = true;
protected string|null $domain = null;
protected Closure|null $cloneUsing = null; // The callback should accept Route instance or the route name (string)
protected Closure|null $shouldClone = null;
@ -177,6 +178,13 @@ class CloneRoutesAsTenant
return $this;
}
public function tenantParameterBeforePrefix(bool $tenantParameterBeforePrefix): static
{
$this->tenantParameterBeforePrefix = $tenantParameterBeforePrefix;
return $this;
}
/** Clone an individual route. */
public function cloneRoute(Route|string $route): static
{
@ -226,7 +234,13 @@ class CloneRoutesAsTenant
$action->put('middleware', $middleware);
if ($this->addTenantParameter) {
$action->put('prefix', $prefix . '/{' . PathTenantResolver::tenantParameterName() . '}');
$tenantParameter = '{' . PathTenantResolver::tenantParameterName() . '}';
$newPrefix = $this->tenantParameterBeforePrefix
? $tenantParameter . '/' . $prefix
: $prefix . '/' . $tenantParameter;
$action->put('prefix', $newPrefix);
}
/** @var Route $newRoute */

View file

@ -32,10 +32,10 @@ class DatabaseTenancyBootstrapper implements TenancyBootstrapper
throw new Exception('The template connection must NOT have URL defined. Specify the connection using individual parts instead of a database URL.');
}
// Better debugging, but breaks cached lookup in prod
if (app()->environment('local') || app()->environment('testing')) { // todo@docs mention this change in v4 upgrade guide https://github.com/archtechx/tenancy/pull/945#issuecomment-1268206149
// Better debugging, but breaks cached lookup, so we disable this in prod
if (app()->environment('local') || app()->environment('testing')) {
$database = $tenant->database()->getName();
if (! $tenant->database()->manager()->databaseExists($database)) { // todo@samuel does this call correctly use the host connection?
if (! $tenant->database()->manager()->databaseExists($database)) {
throw new TenantDatabaseDoesNotExistException($database);
}
}

View file

@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
namespace Stancl\Tenancy\Bootstrappers;
use Illuminate\Config\Repository;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
use Stancl\Tenancy\Contracts\Tenant;
class TenantConfigBootstrapper implements TenancyBootstrapper
{
public array $originalConfig = [];
/** @var array<string, string|array> */
public static array $storageToConfigMap = [
// 'paypal_api_key' => 'services.paypal.api_key',
];
public function __construct(
protected Repository $config,
) {}
public function bootstrap(Tenant $tenant): void
{
foreach (static::$storageToConfigMap as $storageKey => $configKey) {
/** @var Tenant&Model $tenant */
$override = Arr::get($tenant, $storageKey);
if (! is_null($override)) {
if (is_array($configKey)) {
foreach ($configKey as $key) {
$this->originalConfig[$key] = $this->originalConfig[$key] ?? $this->config->get($key);
$this->config->set($key, $override);
}
} else {
$this->originalConfig[$configKey] = $this->originalConfig[$configKey] ?? $this->config->get($configKey);
$this->config->set($configKey, $override);
}
}
}
}
public function revert(): void
{
foreach ($this->originalConfig as $key => $value) {
$this->config->set($key, $value);
}
}
}

View file

@ -8,7 +8,7 @@ use Illuminate\Console\Command;
class CreatePendingTenants extends Command
{
protected $signature = 'tenants:pending-create {--count= : The number of pending tenants to be created}';
protected $signature = 'tenants:pending-create {--count= : The number of pending tenants to maintain}';
protected $description = 'Create pending tenants.';

View file

@ -81,12 +81,19 @@ class CreateUserWithRLSPolicies extends Command
#[\SensitiveParameter]
string $password,
): DatabaseConfig {
// This is a bit of a hack. We want to use our existing createUser() logic.
// That logic needs a DatabaseConfig instance. However, we aren't really working
// with any specific tenant here. We also *don't* want to use anything tenant-specific
// here. We are creating the SHARED "RLS user". Therefore, we need a custom DatabaseConfig
// instance for this purpose. The easiest way to do that is to grab an empty Tenant model
// (we use TenantWithDatabase in RLS) and manually create the host connection, just like
// DatabaseConfig::manager() would. We don't call that method since we want to use our existing
// PermissionControlledPostgreSQLSchemaManager $manager instance, rather than the "tenant's manager".
/** @var TenantWithDatabase $tenantModel */
$tenantModel = tenancy()->model();
// Use a temporary DatabaseConfig instance to set the host connection
$temporaryDbConfig = $tenantModel->database();
$temporaryDbConfig->purgeHostConnection();
$tenantHostConnectionName = $temporaryDbConfig->getTenantHostConnectionName();

View file

@ -6,6 +6,7 @@ namespace Stancl\Tenancy\Commands;
use Closure;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Process;
class Install extends Command
{
@ -128,14 +129,27 @@ class Install extends Command
public function askForSupport(): void
{
if ($this->components->confirm('Would you like to show your support by starring the project on GitHub?', true)) {
if (PHP_OS_FAMILY === 'Darwin') {
exec('open https://github.com/archtechx/tenancy');
$ghVersion = Process::run('gh --version');
$starred = false;
// Make sure the `gh` binary is the actual GitHub CLI and not an unrelated tool
if ($ghVersion->successful() && str_contains($ghVersion->output(), 'https://github.com/cli/cli')) {
$starRequest = Process::run('gh api -X PUT user/starred/archtechx/tenancy');
$starred = $starRequest->successful();
}
if (PHP_OS_FAMILY === 'Windows') {
exec('start https://github.com/archtechx/tenancy');
}
if (PHP_OS_FAMILY === 'Linux') {
exec('xdg-open https://github.com/archtechx/tenancy');
if ($starred) {
$this->components->success('Repository starred via gh CLI, thank you!');
} else {
if (PHP_OS_FAMILY === 'Darwin') {
exec('open https://github.com/archtechx/tenancy');
}
if (PHP_OS_FAMILY === 'Windows') {
exec('start https://github.com/archtechx/tenancy');
}
if (PHP_OS_FAMILY === 'Linux') {
exec('xdg-open https://github.com/archtechx/tenancy');
}
}
}
}

View file

@ -4,10 +4,8 @@ declare(strict_types=1);
namespace Stancl\Tenancy\Contracts;
use Stancl\Tenancy\Tenancy;
/** Additional features, like Telescope tags and tenant redirects. */
interface Feature
{
public function bootstrap(Tenancy $tenancy): void;
public function bootstrap(): void;
}

View file

@ -28,7 +28,8 @@ trait HasDatabase
}
if ($key === $this->internalPrefix() . 'db_connection') {
// Remove DB connection because that's not used here
// Remove DB connection because that's not used for the connection *contents*.
// Instead the code uses getInternal('db_connection').
continue;
}

View file

@ -6,14 +6,13 @@ namespace Stancl\Tenancy\Database\Concerns;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Stancl\Tenancy\Contracts\Tenant;
use Stancl\Tenancy\Events\CreatingPendingTenant;
use Stancl\Tenancy\Events\PendingTenantCreated;
use Stancl\Tenancy\Events\PendingTenantPulled;
use Stancl\Tenancy\Events\PullingPendingTenant;
// todo consider adding a method that sets pending_since to null — to flag tenants as not-pending
/**
* @property ?Carbon $pending_since
*
@ -50,46 +49,62 @@ trait HasPending
*/
public static function createPending(array $attributes = []): Model&Tenant
{
$tenant = static::create($attributes);
event(new CreatingPendingTenant($tenant));
// Update the pending_since value only after the tenant is created so it's
// Not marked as pending until finishing running the migrations, seeders, etc.
$tenant->update([
'pending_since' => now()->timestamp,
]);
try {
$tenant = static::create($attributes);
event(new CreatingPendingTenant($tenant));
} finally {
// Update the pending_since value only after the tenant is created so it's
// not marked as pending until after migrations, seeders, etc are run.
$tenant->update([
'pending_since' => now()->timestamp,
]);
}
event(new PendingTenantCreated($tenant));
return $tenant;
}
/** Pull a pending tenant. */
public static function pullPending(): Model&Tenant
/**
* Pull a pending tenant from the pool or create a new one if the pool is empty.
*
* @param array $attributes The attributes to set on the tenant.
*/
public static function pullPending(array $attributes = []): Model&Tenant
{
/** @var Model&Tenant $pendingTenant */
$pendingTenant = static::pullPendingFromPool(true);
$pendingTenant = static::pullPendingFromPool(true, $attributes);
return $pendingTenant;
}
/** Try to pull a tenant from the pool of pending tenants. */
public static function pullPendingFromPool(bool $firstOrCreate = true, array $attributes = []): ?Tenant
/**
* Try to pull a tenant from the pool of pending tenants.
*
* @param bool $firstOrCreate If true, a tenant will be *created* if the pool is empty. Otherwise null is returned.
* @param array $attributes The attributes to set on the tenant.
*/
public static function pullPendingFromPool(bool $firstOrCreate = false, array $attributes = []): ?Tenant
{
/** @var (Model&Tenant)|null $tenant */
$tenant = static::onlyPending()->first();
$tenant = DB::transaction(function () use ($attributes): ?Tenant {
/** @var (Model&Tenant)|null $tenant */
$tenant = static::onlyPending()->first();
if ($tenant !== null) {
event(new PullingPendingTenant($tenant));
$tenant->update(array_merge($attributes, [
'pending_since' => null,
]));
}
return $tenant;
});
if ($tenant === null) {
return $firstOrCreate ? static::create($attributes) : null;
}
event(new PullingPendingTenant($tenant));
$tenant->update(array_merge($attributes, [
'pending_since' => null,
]));
// Only triggered if a tenant that was pulled from the pool is returned
event(new PendingTenantPulled($tenant));
return $tenant;

View file

@ -13,7 +13,6 @@ use Stancl\Tenancy\Database\Contracts\TenantWithDatabase as Tenant;
use Stancl\Tenancy\Database\Exceptions\DatabaseManagerNotRegisteredException;
use Stancl\Tenancy\Database\Exceptions\NoConnectionSetException;
// todo@dbRefactor refactor host connection logic to make customizing the host connection easier
class DatabaseConfig
{
/** The tenant whose database we're dealing with. */
@ -115,7 +114,7 @@ class DatabaseConfig
{
$this->tenant->setInternal('db_name', $this->getName());
if ($this->connectionDriverManager($this->getTemplateConnectionDriver()) instanceof Contracts\ManagesDatabaseUsers) {
if ($this->managerForDriver($this->getTemplateConnectionDriver()) instanceof Contracts\ManagesDatabaseUsers) {
$this->tenant->setInternal('db_username', $this->getUsername() ?? (static::$usernameGenerator)($this->tenant, $this));
$this->tenant->setInternal('db_password', $this->getPassword() ?? (static::$passwordGenerator)($this->tenant, $this));
}
@ -137,7 +136,9 @@ class DatabaseConfig
}
if ($template = config('tenancy.database.template_tenant_connection')) {
return is_array($template) ? array_merge($this->getCentralConnection(), $template) : config("database.connections.{$template}");
return is_array($template)
? array_merge($this->getCentralConnection(), $template)
: config("database.connections.{$template}");
}
return $this->getCentralConnection();
@ -176,10 +177,10 @@ class DatabaseConfig
$config = $this->tenantConfig;
$templateConnection = $this->getTemplateConnection();
if ($this->connectionDriverManager($this->getTemplateConnectionDriver()) instanceof Contracts\ManagesDatabaseUsers) {
// We're removing the username and password because user with these credentials is not created yet
// If you need to provide username and password when using PermissionControlledMySQLDatabaseManager,
// consider creating a new connection and use it as `tenancy_db_connection` tenant config key
if ($this->managerForDriver($this->getTemplateConnectionDriver()) instanceof Contracts\ManagesDatabaseUsers) {
// We remove the username and password because the user with these credentials is not yet created.
// If you need to provide a username and a password when using a permission controlled database manager,
// consider creating a new connection and use it as `tenancy_db_connection`.
unset($config['username'], $config['password']);
}
@ -191,7 +192,7 @@ class DatabaseConfig
}
/**
* Purge the previous tenant connection before opening it for another tenant.
* Purge the previous host connection before opening it for another tenant.
*/
public function purgeHostConnection(): void
{
@ -199,20 +200,20 @@ class DatabaseConfig
}
/**
* Get the TenantDatabaseManager for this tenant's connection.
* Get the TenantDatabaseManager for this tenant's host connection.
*
* @throws NoConnectionSetException|DatabaseManagerNotRegisteredException
*/
public function manager(): Contracts\TenantDatabaseManager
{
// Laravel caches the previous PDO connection, so we purge it to be able to change the connection details
// Laravel persists the PDO connection, so we purge it to be able to change the connection details
$this->purgeHostConnection();
// Create the tenant host connection config
$tenantHostConnectionName = $this->getTenantHostConnectionName();
config(["database.connections.{$tenantHostConnectionName}" => $this->hostConnection()]);
$manager = $this->connectionDriverManager(config("database.connections.{$tenantHostConnectionName}.driver"));
$manager = $this->managerForDriver(config("database.connections.{$tenantHostConnectionName}.driver"));
if ($manager instanceof Contracts\StatefulTenantDatabaseManager) {
$manager->setConnection($tenantHostConnectionName);
@ -222,12 +223,11 @@ class DatabaseConfig
}
/**
* todo@name come up with a better name
* Get database manager class from the given connection config's driver.
* Get the TenantDatabaseManager for a given database driver.
*
* @throws DatabaseManagerNotRegisteredException
*/
protected function connectionDriverManager(string $driver): Contracts\TenantDatabaseManager
protected function managerForDriver(string $driver): Contracts\TenantDatabaseManager
{
$databaseManagers = config('tenancy.database.managers');

View file

@ -23,7 +23,6 @@ class PermissionControlledMySQLDatabaseManager extends MySQLDatabaseManager impl
{
$database = $databaseConfig->getName();
$username = $databaseConfig->getUsername();
$hostname = $databaseConfig->connection()['host'];
$password = $databaseConfig->getPassword();
$this->connection()->statement("CREATE USER `{$username}`@`%` IDENTIFIED BY '{$password}'");

View file

@ -30,10 +30,6 @@ class PermissionControlledPostgreSQLSchemaManager extends PostgreSQLSchemaManage
$tables = $this->connection()->select("SELECT table_name FROM information_schema.tables WHERE table_schema = '{$schema}' AND table_type = 'BASE TABLE'");
// Grant permissions to any existing tables. This is used with RLS
// todo@samuel refactor this along with the todo in TenantDatabaseManager
// and move the grantPermissions() call inside the condition in `ManagesPostgresUsers::createUser()`
// but maybe moving it inside $createUser is wrong because some central user may migrate new tables
// while the RLS user should STILL get access to those tables
foreach ($tables as $table) {
$tableName = $table->table_name;

View file

@ -4,7 +4,6 @@ declare(strict_types=1);
namespace Stancl\Tenancy\Database\TenantDatabaseManagers;
use AssertionError;
use Closure;
use Illuminate\Database\Eloquent\Model;
use PDO;
@ -15,17 +14,12 @@ use Throwable;
class SQLiteDatabaseManager implements TenantDatabaseManager
{
/**
* SQLite Database path without ending slash.
* SQLite database directory path.
*
* Defaults to database_path().
*/
public static string|null $path = null;
/**
* Should the WAL journal mode be used for newly created databases.
*
* @see https://www.sqlite.org/pragma.html#pragma_journal_mode
*/
public static bool $WAL = true;
/*
* If this isn't null, a connection to the tenant DB will be created
* and passed to the provided closure, for the purpose of keeping the
@ -89,25 +83,7 @@ class SQLiteDatabaseManager implements TenantDatabaseManager
return true;
}
try {
if (file_put_contents($path = $this->getPath($name), '') === false) {
return false;
}
if (static::$WAL) {
$pdo = new PDO('sqlite:' . $path);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// @phpstan-ignore-next-line method.nonObject
assert($pdo->query('pragma journal_mode = wal')->fetch(PDO::FETCH_ASSOC)['journal_mode'] === 'wal', 'Unable to set journal mode to wal.');
}
return true;
} catch (AssertionError $e) {
throw $e;
} catch (Throwable) {
return false;
}
return file_put_contents($this->getPath($name), '') !== false;
}
public function deleteDatabase(TenantWithDatabase $tenant): bool
@ -122,8 +98,16 @@ class SQLiteDatabaseManager implements TenantDatabaseManager
return true;
}
$path = $this->getPath($name);
try {
return unlink($this->getPath($name));
unlink($path . '-journal');
unlink($path . '-wal');
unlink($path . '-shm');
} catch (Throwable) {}
try {
return unlink($path);
} catch (Throwable) {
return false;
}
@ -150,15 +134,10 @@ class SQLiteDatabaseManager implements TenantDatabaseManager
return $baseConfig;
}
public function setConnection(string $connection): void
{
//
}
public function getPath(string $name): string
{
if (static::$path) {
return static::$path . DIRECTORY_SEPARATOR . $name;
return rtrim(static::$path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $name;
}
return database_path($name);

View file

@ -4,4 +4,9 @@ declare(strict_types=1);
namespace Stancl\Tenancy\Events;
/**
* Importantly, listeners for this event should not switch tenancy context.
*
* This event is fired from within a database transaction.
*/
class PullingPendingTenant extends Contracts\TenantEvent {}

View file

@ -6,11 +6,10 @@ namespace Stancl\Tenancy\Features;
use Illuminate\Http\RedirectResponse;
use Stancl\Tenancy\Contracts\Feature;
use Stancl\Tenancy\Tenancy;
class CrossDomainRedirect implements Feature
{
public function bootstrap(Tenancy $tenancy): void
public function bootstrap(): void
{
RedirectResponse::macro('domain', function (string $domain) {
/** @var RedirectResponse $this */

View file

@ -4,20 +4,17 @@ declare(strict_types=1);
namespace Stancl\Tenancy\Features;
use Exception;
use Illuminate\Database\Connectors\ConnectionFactory;
use Illuminate\Database\SQLiteConnection;
use Illuminate\Support\Facades\DB;
use PDO;
use Stancl\Tenancy\Contracts\Feature;
use Stancl\Tenancy\Tenancy;
class DisallowSqliteAttach implements Feature
{
protected static bool|null $loadExtensionSupported = null;
public static string|false|null $extensionPath = null;
public function bootstrap(Tenancy $tenancy): void
public function bootstrap(): void
{
// Handle any already resolved connections
foreach (DB::getConnections() as $connection) {
@ -39,31 +36,29 @@ class DisallowSqliteAttach implements Feature
protected function loadExtension(PDO $pdo): bool
{
if (static::$loadExtensionSupported === null) {
static::$loadExtensionSupported = method_exists($pdo, 'loadExtension');
}
// todo@php85 In PHP 8.5, we can use setAuthorizer() instead of loading an extension.
// However, this is currently blocked on https://github.com/phpredis/phpredis/issues/2688
static $loadExtensionSupported = method_exists($pdo, 'loadExtension');
if (static::$loadExtensionSupported === false) {
return false;
}
if (static::$extensionPath === false) {
return false;
}
if ((! $loadExtensionSupported) ||
(static::$extensionPath === false) ||
(PHP_INT_SIZE !== 8)
) return false;
$suffix = match (PHP_OS_FAMILY) {
'Linux' => 'so',
'Windows' => 'dll',
'Darwin' => 'dylib',
default => throw new Exception("The DisallowSqliteAttach feature doesn't support your operating system: " . PHP_OS_FAMILY),
default => 'error',
};
if ($suffix === 'error') return false;
$arch = php_uname('m');
$arm = $arch === 'aarch64' || $arch === 'arm64';
static::$extensionPath ??= realpath(base_path('vendor/stancl/tenancy/extensions/lib/' . ($arm ? 'arm/' : '') . 'noattach.' . $suffix));
if (static::$extensionPath === false) {
return false;
}
if (static::$extensionPath === false) return false;
$pdo->loadExtension(static::$extensionPath); // @phpstan-ignore method.notFound

View file

@ -7,11 +7,10 @@ namespace Stancl\Tenancy\Features;
use Laravel\Telescope\IncomingEntry;
use Laravel\Telescope\Telescope;
use Stancl\Tenancy\Contracts\Feature;
use Stancl\Tenancy\Tenancy;
class TelescopeTags implements Feature
{
public function bootstrap(Tenancy $tenancy): void
public function bootstrap(): void
{
if (! class_exists(Telescope::class)) {
return;

View file

@ -12,8 +12,10 @@ use Stancl\Tenancy\Contracts\Feature;
use Stancl\Tenancy\Contracts\Tenant;
use Stancl\Tenancy\Events\RevertedToCentralContext;
use Stancl\Tenancy\Events\TenancyBootstrapped;
use Stancl\Tenancy\Tenancy;
// todo@release remove this class
/** @deprecated Use the TenantConfigBootstrapper instead. */
class TenantConfig implements Feature
{
public array $originalConfig = [];
@ -27,7 +29,7 @@ class TenantConfig implements Feature
protected Repository $config,
) {}
public function bootstrap(Tenancy $tenancy): void
public function bootstrap(): void
{
Event::listen(TenancyBootstrapped::class, function (TenancyBootstrapped $event) {
/** @var Tenant $tenant */

View file

@ -17,9 +17,9 @@ class UserImpersonation implements Feature
/** The lifespan of impersonation tokens (in seconds). */
public static int $ttl = 60;
public function bootstrap(Tenancy $tenancy): void
public function bootstrap(): void
{
$tenancy->macro('impersonate', function (Tenant $tenant, string $userId, string $redirectUrl, string|null $authGuard = null, bool $remember = false): Model {
Tenancy::macro('impersonate', function (Tenant $tenant, string $userId, string $redirectUrl, string|null $authGuard = null, bool $remember = false): Model {
return UserImpersonation::modelClass()::create([
Tenancy::tenantKeyColumn() => $tenant->getTenantKey(),
'user_id' => $userId,

View file

@ -7,19 +7,14 @@ namespace Stancl\Tenancy\Features;
use Illuminate\Foundation\Application;
use Illuminate\Support\Facades\Vite;
use Stancl\Tenancy\Contracts\Feature;
use Stancl\Tenancy\Tenancy;
class ViteBundler implements Feature
{
/** @var Application */
protected $app;
public function __construct(
protected Application $app,
) {}
public function __construct(Application $app)
{
$this->app = $app;
}
public function bootstrap(Tenancy $tenancy): void
public function bootstrap(): void
{
Vite::createAssetPathsUsing(function ($path, $secure = null) {
return global_asset($path);

View file

@ -66,9 +66,11 @@ class PreventAccessFromUnwantedDomains
return in_array($request->getHost(), config('tenancy.identification.central_domains'), true);
}
// todo@samuel technically not an identification middleware but probably ok to keep this here
public function requestHasTenant(Request $request): bool
{
// This middleware is special in that it's not an identification middleware
// but still uses some logic from UsableWithEarlyIdentification, so we just
// need to implement this method here. It doesn't matter what it returns.
return false;
}
}

View file

@ -110,7 +110,7 @@ class TenancyUrlGenerator extends UrlGenerator
*/
public function route($name, $parameters = [], $absolute = true)
{
if ($name instanceof BackedEnum && ! is_string($name = $name->value)) { // @phpstan-ignore function.impossibleType
if ($name instanceof BackedEnum && ! is_string($name = $name->value)) {
throw new InvalidArgumentException('Attribute [name] expects a string backed enum.');
}
@ -125,7 +125,7 @@ class TenancyUrlGenerator extends UrlGenerator
*/
public function temporarySignedRoute($name, $expiration, $parameters = [], $absolute = true)
{
if ($name instanceof BackedEnum && ! is_string($name = $name->value)) { // @phpstan-ignore function.impossibleType
if ($name instanceof BackedEnum && ! is_string($name = $name->value)) {
throw new InvalidArgumentException('Attribute [name] expects a string backed enum.');
}

View file

@ -11,6 +11,7 @@ use Illuminate\Foundation\Bus\PendingDispatch;
use Illuminate\Support\Traits\Macroable;
use Stancl\Tenancy\Concerns\DealsWithRouteContexts;
use Stancl\Tenancy\Concerns\ManagesRLSPolicies;
use Stancl\Tenancy\Contracts\Feature;
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
use Stancl\Tenancy\Contracts\Tenant;
use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedByIdException;
@ -40,7 +41,7 @@ class Tenancy
public static array $findWith = [];
/**
* A list of bootstrappers that have been initialized.
* List of bootstrappers that have been initialized.
*
* This is used when reverting tenancy, mainly if an exception
* occurs during bootstrapping, to ensure we don't revert
@ -53,6 +54,23 @@ class Tenancy
*/
public array $initializedBootstrappers = [];
/**
* List of features that have been bootstrapped.
*
* Since features may be bootstrapped multiple times during
* the request cycle (in TSP::boot() and any other times the user calls
* bootstrapFeatures()), we keep track of which features have already
* been bootstrapped so we do not bootstrap them again. Features are
* bootstrapped once and irreversible.
*
* The main point of this is that some features *need* to be bootstrapped
* very early (see #949), so we bootstrap them directly in TSP, but we
* also need the ability to *change* which features are used at runtime
* (mainly tests of this package) and bootstrap features again after making
* changes to config('tenancy.features').
*/
protected array $bootstrappedFeatures = [];
/** Initialize tenancy for the passed tenant. */
public function initialize(Tenant|int|string $tenant): void
{
@ -136,7 +154,7 @@ class Tenancy
public function getBootstrappers(): array
{
// If no callback for getting bootstrappers is set, we return the ones in config.
$resolve = $this->getBootstrappersUsing ?? function (Tenant $tenant) {
$resolve = $this->getBootstrappersUsing ?? function (?Tenant $tenant) {
return config('tenancy.bootstrappers');
};
@ -154,6 +172,26 @@ class Tenancy
return in_array($bootstrapper, static::getBootstrappers(), true);
}
/**
* Bootstrap configured Tenancy features.
*
* Normally, features are bootstrapped directly in TSP::boot(). However, if
* new features are enabled at runtime (e.g. during tests), this method may
* be called to bootstrap new features. It's idempotent and keeps track of
* which features have already been bootstrapped. Keep in mind that feature
* bootstrapping is irreversible.
*/
public function bootstrapFeatures(): void
{
foreach (config('tenancy.features') ?? [] as $feature) {
/** @var class-string<Feature> $feature */
if (! in_array($feature, $this->bootstrappedFeatures)) {
app($feature)->bootstrap();
$this->bootstrappedFeatures[] = $feature;
}
}
}
/**
* @return Builder<Tenant&Model>
*/

View file

@ -40,15 +40,6 @@ class TenancyServiceProvider extends ServiceProvider
// Make sure Tenancy is stateful.
$this->app->singleton(Tenancy::class);
// Make sure features are bootstrapped as soon as Tenancy is instantiated.
$this->app->extend(Tenancy::class, function (Tenancy $tenancy) {
foreach ($this->app['config']['tenancy.features'] ?? [] as $feature) {
$this->app[$feature]->bootstrap($tenancy);
}
return $tenancy;
});
// Make it possible to inject the current tenant by type hinting the Tenant contract.
$this->app->bind(Tenant::class, function ($app) {
return $app[Tenancy::class]->tenant;
@ -176,6 +167,11 @@ class TenancyServiceProvider extends ServiceProvider
return $instance;
});
// Bootstrap features that are already enabled in the config.
// If more features are enabled at runtime, this method may be called
// multiple times, it keeps track of which features have already been bootstrapped.
$this->app->make(Tenancy::class)->bootstrapFeatures();
Route::middlewareGroup('clone', []);
Route::middlewareGroup('universal', []);
Route::middlewareGroup('tenant', []);