mirror of
https://github.com/archtechx/tenancy.git
synced 2026-02-04 17:44:05 +00:00
Merge branch 'master' into impersonation-token-cleanup
This commit is contained in:
commit
69a1326029
68 changed files with 1336 additions and 367 deletions
|
|
@ -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 */
|
||||
|
|
|
|||
|
|
@ -99,11 +99,21 @@ class CacheTenancyBootstrapper implements TenancyBootstrapper
|
|||
{
|
||||
$names = $this->config->get('tenancy.cache.stores');
|
||||
|
||||
if (
|
||||
$this->config->get('tenancy.cache.scope_sessions', true) &&
|
||||
in_array($this->config->get('session.driver'), ['redis', 'memcached', 'dynamodb', 'apc'], true)
|
||||
) {
|
||||
$names[] = $this->getSessionCacheStoreName();
|
||||
if ($this->config->get('tenancy.cache.scope_sessions', true)) {
|
||||
// These are the only cache driven session backends (see Laravel's config/session.php)
|
||||
if (! in_array($this->config->get('session.driver'), ['redis', 'memcached', 'dynamodb', 'apc'], true)) {
|
||||
if (app()->environment('production')) {
|
||||
// We only throw this exception in prod to make configuration a little easier. Developers
|
||||
// may have scope_sessions set to true while using different session drivers e.g. in tests.
|
||||
// Previously we just silently ignored this, however since session scoping is of high importance
|
||||
// in production, we make sure to notify the developer, by throwing an exception, that session
|
||||
// scoping isn't happening as expected/configured due to an incompatible session driver.
|
||||
throw new Exception('Session driver [' . $this->config->get('session.driver') . '] cannot be scoped by tenancy.cache.scope_session');
|
||||
}
|
||||
} else {
|
||||
// Scoping sessions using this bootstrapper implicitly adds the session store to $names
|
||||
$names[] = $this->getSessionCacheStoreName();
|
||||
}
|
||||
}
|
||||
|
||||
$names = array_unique($names);
|
||||
|
|
@ -112,6 +122,7 @@ class CacheTenancyBootstrapper implements TenancyBootstrapper
|
|||
$store = $this->config->get("cache.stores.{$name}");
|
||||
|
||||
if ($store === null || $store['driver'] === 'file') {
|
||||
// 'file' stores are ignored here and instead handled by FilesystemTenancyBootstrapper
|
||||
return false;
|
||||
}
|
||||
|
||||
|
|
|
|||
123
src/Bootstrappers/DatabaseCacheBootstrapper.php
Normal file
123
src/Bootstrappers/DatabaseCacheBootstrapper.php
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Bootstrappers;
|
||||
|
||||
use Exception;
|
||||
use Illuminate\Cache\CacheManager;
|
||||
use Illuminate\Cache\DatabaseStore;
|
||||
use Illuminate\Config\Repository;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
|
||||
use Stancl\Tenancy\Contracts\Tenant;
|
||||
use Stancl\Tenancy\TenancyServiceProvider;
|
||||
|
||||
/**
|
||||
* This bootstrapper allows cache to be stored in tenant databases by switching the database
|
||||
* connection used by cache stores that use the database driver.
|
||||
*
|
||||
* Can be used instead of CacheTenancyBootstrapper.
|
||||
*
|
||||
* By default, this bootstrapper scopes ALL cache stores that use the database driver. If you only
|
||||
* want to scope SOME stores, set the static $stores property to an array of names of the stores
|
||||
* you want to scope. These stores must use 'database' as their driver.
|
||||
*
|
||||
* Notably, this bootstrapper sets TenancyServiceProvider::$adjustCacheManagerUsing to a callback
|
||||
* that ensures all affected stores still use the central connection when accessed via global cache
|
||||
* (typicaly the GlobalCache facade or global_cache() helper).
|
||||
*/
|
||||
class DatabaseCacheBootstrapper implements TenancyBootstrapper
|
||||
{
|
||||
/**
|
||||
* Cache stores to scope.
|
||||
*
|
||||
* If null, all cache stores that use the database driver will be scoped.
|
||||
* If an array, only the specified stores will be scoped. These all must use the database driver.
|
||||
*/
|
||||
public static array|null $stores = null;
|
||||
|
||||
/**
|
||||
* Should scoped stores be adjusted on the global cache manager to use the central connection.
|
||||
*
|
||||
* You may want to set this to false if you don't use the built-in global cache and instead provide
|
||||
* a list of stores to scope (static::$stores), with your own global store excluded that you then
|
||||
* use manually. But in such a scenario you likely wouldn't be using global cache at all which means
|
||||
* the callbacks for adjusting it wouldn't be executed in the first place.
|
||||
*/
|
||||
public static bool $adjustGlobalCacheManager = true;
|
||||
|
||||
public function __construct(
|
||||
protected Repository $config,
|
||||
protected CacheManager $cache,
|
||||
protected array $originalConnections = [],
|
||||
protected array $originalLockConnections = []
|
||||
) {}
|
||||
|
||||
public function bootstrap(Tenant $tenant): void
|
||||
{
|
||||
if (! config('database.connections.tenant')) {
|
||||
throw new Exception('DatabaseCacheBootstrapper must run after DatabaseTenancyBootstrapper.');
|
||||
}
|
||||
|
||||
$stores = $this->scopedStoreNames();
|
||||
|
||||
foreach ($stores as $storeName) {
|
||||
$this->originalConnections[$storeName] = $this->config->get("cache.stores.{$storeName}.connection");
|
||||
$this->originalLockConnections[$storeName] = $this->config->get("cache.stores.{$storeName}.lock_connection");
|
||||
|
||||
$this->config->set("cache.stores.{$storeName}.connection", 'tenant');
|
||||
$this->config->set("cache.stores.{$storeName}.lock_connection", 'tenant');
|
||||
|
||||
$this->cache->purge($storeName);
|
||||
}
|
||||
|
||||
if (static::$adjustGlobalCacheManager) {
|
||||
// Preferably we'd try to respect the original value of this static property -- store it in a variable,
|
||||
// pull it into the closure, and execute it there. But such a naive approach would lead to existing callbacks
|
||||
// *from here* being executed repeatedly in a loop on reinitialization. For that reason we do not do that
|
||||
// (this is our only use of $adjustCacheManagerUsing anyway) but ideally at some point we'd have a better solution.
|
||||
$originalConnections = array_combine($stores, array_map(fn (string $storeName) => [
|
||||
'connection' => $this->originalConnections[$storeName] ?? config('tenancy.database.central_connection'),
|
||||
'lockConnection' => $this->originalLockConnections[$storeName] ?? config('tenancy.database.central_connection'),
|
||||
], $stores));
|
||||
|
||||
TenancyServiceProvider::$adjustCacheManagerUsing = static function (CacheManager $manager) use ($originalConnections) {
|
||||
foreach ($originalConnections as $storeName => $connections) {
|
||||
/** @var DatabaseStore $store */
|
||||
$store = $manager->store($storeName)->getStore();
|
||||
|
||||
$store->setConnection(DB::connection($connections['connection']));
|
||||
$store->setLockConnection(DB::connection($connections['lockConnection']));
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public function revert(): void
|
||||
{
|
||||
foreach ($this->originalConnections as $storeName => $originalConnection) {
|
||||
$this->config->set("cache.stores.{$storeName}.connection", $originalConnection);
|
||||
$this->config->set("cache.stores.{$storeName}.lock_connection", $this->originalLockConnections[$storeName]);
|
||||
|
||||
$this->cache->purge($storeName);
|
||||
}
|
||||
|
||||
TenancyServiceProvider::$adjustCacheManagerUsing = null;
|
||||
}
|
||||
|
||||
protected function scopedStoreNames(): array
|
||||
{
|
||||
return array_filter(
|
||||
static::$stores ?? array_keys($this->config->get('cache.stores', [])),
|
||||
function ($storeName) {
|
||||
$store = $this->config->get("cache.stores.{$storeName}");
|
||||
|
||||
if (! $store) return false;
|
||||
if (! isset($store['driver'])) return false;
|
||||
|
||||
return $store['driver'] === 'database';
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
54
src/Bootstrappers/TenantConfigBootstrapper.php
Normal file
54
src/Bootstrappers/TenantConfigBootstrapper.php
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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.';
|
||||
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -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');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -51,13 +51,24 @@ class Migrate extends MigrateCommand
|
|||
return 1;
|
||||
}
|
||||
|
||||
if ($this->getProcesses() > 1) {
|
||||
return $this->runConcurrently($this->getTenantChunks()->map(function ($chunk) {
|
||||
return $this->getTenants($chunk);
|
||||
}));
|
||||
$originalTemplateConnection = config('tenancy.database.template_tenant_connection');
|
||||
|
||||
if ($database = $this->input->getOption('database')) {
|
||||
config(['tenancy.database.template_tenant_connection' => $database]);
|
||||
}
|
||||
|
||||
return $this->migrateTenants($this->getTenants()) ? 0 : 1;
|
||||
if ($this->getProcesses() > 1) {
|
||||
$code = $this->runConcurrently($this->getTenantChunks()->map(function ($chunk) {
|
||||
return $this->getTenants($chunk);
|
||||
}));
|
||||
} else {
|
||||
$code = $this->migrateTenants($this->getTenants()) ? 0 : 1;
|
||||
}
|
||||
|
||||
// Reset the template tenant connection to the original one
|
||||
config(['tenancy.database.template_tenant_connection' => $originalTemplateConnection]);
|
||||
|
||||
return $code;
|
||||
}
|
||||
|
||||
protected function childHandle(mixed ...$args): bool
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ declare(strict_types=1);
|
|||
|
||||
namespace Stancl\Tenancy\Commands;
|
||||
|
||||
use Illuminate\Console\ConfirmableTrait;
|
||||
use Illuminate\Database\Console\Migrations\BaseCommand;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Support\LazyCollection;
|
||||
|
|
@ -17,7 +18,7 @@ use Symfony\Component\Console\Output\OutputInterface as OI;
|
|||
|
||||
class MigrateFresh extends BaseCommand
|
||||
{
|
||||
use HasTenantOptions, DealsWithMigrations, ParallelCommand;
|
||||
use HasTenantOptions, DealsWithMigrations, ParallelCommand, ConfirmableTrait;
|
||||
|
||||
protected $description = 'Drop all tables and re-run all migrations for tenant(s)';
|
||||
|
||||
|
|
@ -27,6 +28,7 @@ class MigrateFresh extends BaseCommand
|
|||
|
||||
$this->addOption('drop-views', null, InputOption::VALUE_NONE, 'Drop views along with tenant tables.', null);
|
||||
$this->addOption('step', null, InputOption::VALUE_NONE, 'Force the migrations to be run so they can be rolled back individually.');
|
||||
$this->addOption('force', null, InputOption::VALUE_NONE, 'Force the command to run when in production.', null);
|
||||
$this->addProcessesOption();
|
||||
|
||||
$this->setName('tenants:migrate-fresh');
|
||||
|
|
@ -34,6 +36,10 @@ class MigrateFresh extends BaseCommand
|
|||
|
||||
public function handle(): int
|
||||
{
|
||||
if (! $this->confirmToProceed()) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
$success = true;
|
||||
|
||||
if ($this->getProcesses() > 1) {
|
||||
|
|
|
|||
|
|
@ -14,10 +14,9 @@ use Illuminate\Support\Arr;
|
|||
use Illuminate\Support\Facades\Route as RouteFacade;
|
||||
use Stancl\Tenancy\Enums\RouteMode;
|
||||
|
||||
// todo@refactor move this logic to some dedicated static class?
|
||||
|
||||
/**
|
||||
* @mixin \Stancl\Tenancy\Tenancy
|
||||
* @internal The public methods in this trait should not be understood to be a public stable API.
|
||||
*/
|
||||
trait DealsWithRouteContexts
|
||||
{
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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');
|
||||
|
||||
|
|
|
|||
|
|
@ -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}'");
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
@ -84,30 +78,13 @@ class SQLiteDatabaseManager implements TenantDatabaseManager
|
|||
// or creating a closure holding a reference to it and passing that to register_shutdown_function().
|
||||
|
||||
$name = '_tenancy_inmemory_' . $tenant->getTenantKey();
|
||||
$tenant->update(['tenancy_db_name' => "file:$name?mode=memory&cache=shared"]);
|
||||
$tenant->setInternal('db_name', "file:$name?mode=memory&cache=shared");
|
||||
$tenant->save();
|
||||
|
||||
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 +99,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 +135,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);
|
||||
|
|
|
|||
|
|
@ -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 {}
|
||||
|
|
|
|||
|
|
@ -8,6 +8,9 @@ use Illuminate\Support\Facades\Cache;
|
|||
|
||||
class GlobalCache extends Cache
|
||||
{
|
||||
/** Make sure this works identically to global_cache() */
|
||||
protected static $cached = false;
|
||||
|
||||
protected static function getFacadeAccessor()
|
||||
{
|
||||
return 'globalCache';
|
||||
|
|
|
|||
|
|
@ -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 */
|
||||
|
|
|
|||
|
|
@ -4,25 +4,22 @@ 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) {
|
||||
if ($connection instanceof SQLiteConnection) {
|
||||
if (! $this->loadExtension($connection->getPdo())) {
|
||||
if (! $this->setAuthorizer($connection->getPdo())) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
|
@ -31,42 +28,54 @@ class DisallowSqliteAttach implements Feature
|
|||
// Apply the change to all sqlite connections resolved in the future
|
||||
DB::extend('sqlite', function ($config, $name) {
|
||||
$conn = app(ConnectionFactory::class)->make($config, $name);
|
||||
$this->loadExtension($conn->getPdo());
|
||||
$this->setAuthorizer($conn->getPdo());
|
||||
|
||||
return $conn;
|
||||
});
|
||||
}
|
||||
|
||||
protected function loadExtension(PDO $pdo): bool
|
||||
protected function setAuthorizer(PDO $pdo): bool
|
||||
{
|
||||
if (static::$loadExtensionSupported === null) {
|
||||
static::$loadExtensionSupported = method_exists($pdo, 'loadExtension');
|
||||
if (PHP_VERSION_ID >= 80500) {
|
||||
$this->setNativeAuthorizer($pdo);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (static::$loadExtensionSupported === false) {
|
||||
return false;
|
||||
}
|
||||
if (static::$extensionPath === false) {
|
||||
return false;
|
||||
}
|
||||
static $loadExtensionSupported = method_exists($pdo, 'loadExtension');
|
||||
|
||||
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
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function setNativeAuthorizer(PDO $pdo): void
|
||||
{
|
||||
// @phpstan-ignore method.notFound
|
||||
$pdo->setAuthorizer(static function (int $action): int {
|
||||
return $action === 24 // SQLITE_ATTACH
|
||||
? PDO\Sqlite::DENY
|
||||
: PDO\Sqlite::OK;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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 */
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -5,22 +5,19 @@ declare(strict_types=1);
|
|||
namespace Stancl\Tenancy\Features;
|
||||
|
||||
use Illuminate\Foundation\Application;
|
||||
use Illuminate\Support\Facades\Vite;
|
||||
use Stancl\Tenancy\Contracts\Feature;
|
||||
use Stancl\Tenancy\Overrides\Vite;
|
||||
use Stancl\Tenancy\Tenancy;
|
||||
|
||||
class ViteBundler implements Feature
|
||||
{
|
||||
/** @var Application */
|
||||
protected $app;
|
||||
public function __construct(
|
||||
protected Application $app,
|
||||
) {}
|
||||
|
||||
public function __construct(Application $app)
|
||||
public function bootstrap(): void
|
||||
{
|
||||
$this->app = $app;
|
||||
}
|
||||
|
||||
public function bootstrap(Tenancy $tenancy): void
|
||||
{
|
||||
$this->app->singleton(\Illuminate\Foundation\Vite::class, Vite::class);
|
||||
Vite::createAssetPathsUsing(function ($path, $secure = null) {
|
||||
return global_asset($path);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -40,7 +40,8 @@ class CreateDatabase implements ShouldQueue
|
|||
|
||||
try {
|
||||
$databaseManager->ensureTenantCanBeCreated($this->tenant);
|
||||
$this->tenant->database()->manager()->createDatabase($this->tenant);
|
||||
$databaseCreated = $this->tenant->database()->manager()->createDatabase($this->tenant);
|
||||
assert($databaseCreated);
|
||||
|
||||
event(new DatabaseCreated($this->tenant));
|
||||
} catch (TenantDatabaseAlreadyExistsException | TenantDatabaseUserAlreadyExistsException $e) {
|
||||
|
|
|
|||
|
|
@ -8,8 +8,6 @@ use Illuminate\Routing\Events\RouteMatched;
|
|||
use Stancl\Tenancy\Enums\RouteMode;
|
||||
use Stancl\Tenancy\Resolvers\PathTenantResolver;
|
||||
|
||||
// todo@earlyIdReview
|
||||
|
||||
/**
|
||||
* Conditionally removes the tenant parameter from matched routes when using kernel path identification.
|
||||
*
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@ namespace Stancl\Tenancy\Middleware;
|
|||
|
||||
use Closure;
|
||||
use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode;
|
||||
use Stancl\Tenancy\Exceptions\TenancyNotInitializedException;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
|
||||
class CheckTenantForMaintenanceMode extends CheckForMaintenanceMode
|
||||
|
|
@ -14,7 +13,13 @@ class CheckTenantForMaintenanceMode extends CheckForMaintenanceMode
|
|||
public function handle($request, Closure $next)
|
||||
{
|
||||
if (! tenant()) {
|
||||
throw new TenancyNotInitializedException;
|
||||
// If there's no tenant, there's no tenant to check for maintenance mode.
|
||||
// Since tenant identification middleware has higher priority than this
|
||||
// middleware, a missing tenant would have already lead to request termination.
|
||||
// (And even if priority were misconfigured, the request would simply get
|
||||
// terminated *after* this middleware.)
|
||||
// Therefore, we are likely on a universal route, in central context.
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
if (tenant('maintenance_mode')) {
|
||||
|
|
|
|||
|
|
@ -11,8 +11,6 @@ use Stancl\Tenancy\Concerns\UsableWithEarlyIdentification;
|
|||
use Stancl\Tenancy\Enums\RouteMode;
|
||||
|
||||
/**
|
||||
* todo@name 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.
|
||||
|
|
@ -68,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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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.');
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,22 +0,0 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Stancl\Tenancy\Overrides;
|
||||
|
||||
use Illuminate\Foundation\Vite as BaseVite;
|
||||
|
||||
class Vite extends BaseVite
|
||||
{
|
||||
/**
|
||||
* Generate an asset path for the application.
|
||||
*
|
||||
* @param string $path
|
||||
* @param bool|null $secure
|
||||
* @return string
|
||||
*/
|
||||
protected function assetPath($path, $secure = null)
|
||||
{
|
||||
return global_asset($path);
|
||||
}
|
||||
}
|
||||
|
|
@ -17,6 +17,9 @@ abstract class CachedTenantResolver implements TenantResolver
|
|||
|
||||
public function __construct(Application $app)
|
||||
{
|
||||
// globalCache should generally not be injected, however in this case
|
||||
// the class is always created from scratch when calling invalidateCache()
|
||||
// meaning the global cache stores are also resolved from scratch.
|
||||
$this->cache = $app->make('globalCache')->store(static::cacheStore());
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
@ -24,11 +25,15 @@ class Tenancy
|
|||
*/
|
||||
public Tenant|null $tenant = null;
|
||||
|
||||
// todo@docblock
|
||||
/**
|
||||
* Custom callback for providing a list of bootstrappers to use.
|
||||
* When this is null, config('tenancy.bootstrappers') is used.
|
||||
* @var ?Closure(): list<TenancyBootstrapper>
|
||||
*/
|
||||
public ?Closure $getBootstrappersUsing = null;
|
||||
|
||||
/** Is tenancy fully initialized? */
|
||||
public bool $initialized = false; // todo@docs document the difference between $tenant being set and $initialized being true (e.g. end of initialize() method)
|
||||
public bool $initialized = false;
|
||||
|
||||
/**
|
||||
* List of relations to eager load when fetching a tenant via tenancy()->find().
|
||||
|
|
@ -36,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
|
||||
|
|
@ -49,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
|
||||
{
|
||||
|
|
@ -117,10 +139,12 @@ class Tenancy
|
|||
return;
|
||||
}
|
||||
|
||||
// We fire both of these events before unsetting tenant so that listeners
|
||||
// to both events can access the current tenant. Having separate events
|
||||
// still has value as it's consistent with our other events and provides
|
||||
// more granularity for event listeners, e.g. for ensuring something runs
|
||||
// before standard TenancyEnded listeners such as RevertToCentralContext.
|
||||
event(new Events\EndingTenancy($this));
|
||||
|
||||
// todo@samuel find a way to refactor these two methods
|
||||
|
||||
event(new Events\TenancyEnded($this));
|
||||
|
||||
$this->tenant = null;
|
||||
|
|
@ -131,12 +155,12 @@ class Tenancy
|
|||
/** @return TenancyBootstrapper[] */
|
||||
public function getBootstrappers(): array
|
||||
{
|
||||
// If no callback for getting bootstrappers is set, we just return all of them.
|
||||
$resolve = $this->getBootstrappersUsing ?? function (Tenant $tenant) {
|
||||
// If no callback for getting bootstrappers is set, we return the ones in config.
|
||||
$resolve = $this->getBootstrappersUsing ?? function (?Tenant $tenant) {
|
||||
return config('tenancy.bootstrappers');
|
||||
};
|
||||
|
||||
// Here We instantiate the bootstrappers and return them.
|
||||
// Here we instantiate the bootstrappers and return them.
|
||||
return array_map('app', $resolve($this->tenant));
|
||||
}
|
||||
|
||||
|
|
@ -150,6 +174,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>
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -23,6 +23,9 @@ class TenancyServiceProvider extends ServiceProvider
|
|||
public static bool $registerForgetTenantParameterListener = true;
|
||||
public static bool $migrateFreshOverride = true;
|
||||
|
||||
/** @internal */
|
||||
public static Closure|null $adjustCacheManagerUsing = null;
|
||||
|
||||
/* Register services. */
|
||||
public function register(): void
|
||||
{
|
||||
|
|
@ -37,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;
|
||||
|
|
@ -81,7 +75,29 @@ class TenancyServiceProvider extends ServiceProvider
|
|||
});
|
||||
|
||||
$this->app->bind('globalCache', function ($app) {
|
||||
return new CacheManager($app);
|
||||
// We create a separate CacheManager to be used for "global" cache -- cache that
|
||||
// is always central, regardless of the current context.
|
||||
//
|
||||
// Importantly, we use a regular binding here, not a singleton. Thanks to that,
|
||||
// any time we resolve this cache manager, we get a *fresh* instance -- an instance
|
||||
// that was not affected by any scoping logic.
|
||||
//
|
||||
// This works great for cache stores that are *directly* scoped, like Redis or
|
||||
// any other tagged or prefixed stores, but it doesn't work for the database driver.
|
||||
//
|
||||
// When we use the DatabaseTenancyBootstrapper, it changes the default connection,
|
||||
// and therefore the connection of the database store that will be created when
|
||||
// this new CacheManager is instantiated again.
|
||||
//
|
||||
// For that reason, we also adjust the relevant stores on this new CacheManager
|
||||
// using the callback below. It is set by DatabaseCacheBootstrapper.
|
||||
$manager = new CacheManager($app);
|
||||
|
||||
if (static::$adjustCacheManagerUsing !== null) {
|
||||
(static::$adjustCacheManagerUsing)($manager);
|
||||
}
|
||||
|
||||
return $manager;
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -152,6 +168,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', []);
|
||||
|
|
|
|||
|
|
@ -36,7 +36,12 @@ if (! function_exists('tenant')) {
|
|||
}
|
||||
|
||||
if (! function_exists('tenant_asset')) {
|
||||
// todo@docblock
|
||||
/**
|
||||
* Generate a URL to an asset in tenant storage.
|
||||
*
|
||||
* If app.asset_url is set, this helper suffixes that URL before appending the asset path.
|
||||
* If it is not set, the stancl.tenancy.asset route is used.
|
||||
*/
|
||||
function tenant_asset(string|null $asset): string
|
||||
{
|
||||
if ($assetUrl = config('app.asset_url')) {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue