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

Merge branch 'master' of https://github.com/archtechx/tenancy into storage-url-conflict-resolution + migrate tests to Pest

This commit is contained in:
lukinovec 2022-07-27 10:54:08 +02:00
commit 8aff44215d
90 changed files with 3867 additions and 3505 deletions

View file

@ -6,6 +6,7 @@ namespace Stancl\Tenancy\Bootstrappers;
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
use Stancl\Tenancy\Contracts\Tenant;
use Stancl\Tenancy\Contracts\TenantWithDatabase;
use Stancl\Tenancy\Database\DatabaseManager;
use Stancl\Tenancy\Exceptions\TenantDatabaseDoesNotExistException;

View file

@ -5,7 +5,6 @@ declare(strict_types=1);
namespace Stancl\Tenancy\Bootstrappers;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Filesystem\FilesystemAdapter;
use Illuminate\Support\Facades\Storage;
use League\Flysystem\Adapter\Local as LocalAdapter;
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
@ -55,37 +54,39 @@ class FilesystemTenancyBootstrapper implements TenancyBootstrapper
}
// Storage facade
foreach ($this->app['config']['tenancy.filesystem.disks'] as $disk) {
/** @var FilesystemAdapter $filesystemDisk */
$filesystemDisk = Storage::disk($disk);
$this->originalPaths['disks']['path'][$disk] = $filesystemDisk->getAdapter()->getPathPrefix();
Storage::forgetDisk($this->app['config']['tenancy.filesystem.disks']);
if ($root = str_replace(
'%storage_path%',
storage_path(),
$this->app['config']["tenancy.filesystem.root_override.{$disk}"] ?? ''
)) {
$filesystemDisk->getAdapter()->setPathPrefix($finalPrefix = $root);
} else {
$root = $this->app['config']["filesystems.disks.{$disk}.root"];
$filesystemDisk->getAdapter()->setPathPrefix($finalPrefix = $root . "/{$suffix}");
foreach ($this->app['config']['tenancy.filesystem.disks'] as $disk) {
// todo@v4 \League\Flysystem\PathPrefixer is making this a lot more painful in flysystem v2
$diskConfig = $this->app['config']["filesystems.disks.{$disk}"];
$originalRoot = $diskConfig['root'] ?? null;
$this->originalPaths['disks']['path'][$disk] = $originalRoot;
$finalPrefix = str_replace(
['%storage_path%', '%tenant%'],
[storage_path(), $tenant->getTenantKey()],
$this->app['config']["tenancy.filesystem.root_override.{$disk}"] ?? '',
);
if (! $finalPrefix) {
$finalPrefix = $originalRoot
? rtrim($originalRoot, '/') . '/' . $suffix
: $suffix;
}
$this->app['config']["filesystems.disks.{$disk}.root"] = $finalPrefix;
// Storage Url
if ($filesystemDisk->getAdapter() instanceof LocalAdapter) {
$config = $filesystemDisk->getDriver()->getConfig();
$this->originalPaths['disks']['url'][$disk] = $config->has('url')
? $config->get('url')
: null;
if ($diskConfig['driver'] === 'local') {
$this->originalPaths['disks']['url'][$disk] = $diskConfig['url'] ?? null;
if ($url = str_replace(
'%tenant_id%',
$tenant->getTenantKey(),
$this->app['config']["tenancy.filesystem.url_override.{$disk}"] ?? ''
)) {
$config->set('url', url($url));
$this->app['config']["filesystems.disks.{$disk}.url"] = url($url);
}
}
}
@ -101,19 +102,16 @@ class FilesystemTenancyBootstrapper implements TenancyBootstrapper
$this->app['url']->setAssetRoot($this->app['config']['app.asset_url']);
// Storage facade
foreach ($this->app['config']['tenancy.filesystem.disks'] as $disk) {
/** @var FilesystemAdapter $filesystemDisk */
$filesystemDisk = Storage::disk($disk);
$root = $this->originalPaths['disks']['path'][$disk];
$filesystemDisk->getAdapter()->setPathPrefix($root);
$this->app['config']["filesystems.disks.{$disk}.root"] = $root;
Storage::forgetDisk($this->app['config']['tenancy.filesystem.disks']);
foreach ($this->app['config']['tenancy.filesystem.disks'] as $diskName) {
$this->app['config']["filesystems.disks.$diskName.root"] = $this->originalPaths['disks']['path'][$diskName];
$diskConfig = $this->app['config']['filesystems.disks.' . $diskName];
// Storage Url
if ($filesystemDisk->getAdapter() instanceof LocalAdapter && ! is_null($this->originalPaths['disks']['url'])) {
$config = $filesystemDisk->getDriver()->getConfig();
$config->set('url', $this->originalPaths['disks']['url']);
$url = $this->originalPaths['disks.url.' . $diskName] ?? null;
if ($diskConfig['driver'] === 'local' && ! is_null($url)) {
$$this->app['config']["filesystems.disks.$diskName.url"] = $url;
}
}
}

View file

@ -7,7 +7,10 @@ namespace Stancl\Tenancy\Bootstrappers;
use Illuminate\Config\Repository;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Queue\Events\JobFailed;
use Illuminate\Queue\Events\JobProcessed;
use Illuminate\Queue\Events\JobProcessing;
use Illuminate\Queue\Events\JobRetryRequested;
use Illuminate\Queue\QueueManager;
use Illuminate\Support\Testing\Fakes\QueueFake;
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
@ -21,6 +24,16 @@ class QueueTenancyBootstrapper implements TenancyBootstrapper
/** @var QueueManager */
protected $queue;
/**
* Don't persist the same tenant across multiple jobs even if they have the same tenant ID.
*
* This is useful when you're changing the tenant's state (e.g. properties in the `data` column) and want the next job to initialize tenancy again
* with the new data. Features like the Tenant Config are only executed when tenancy is initialized, so the re-initialization is needed in some cases.
*
* @var bool
*/
public static $forceRefresh = false;
/**
* The normal constructor is only executed after tenancy is bootstrapped.
* However, we're registering a hook to initialize tenancy. Therefore,
@ -28,7 +41,7 @@ class QueueTenancyBootstrapper implements TenancyBootstrapper
*/
public static function __constructStatic(Application $app)
{
static::setUpJobListener($app->make(Dispatcher::class));
static::setUpJobListener($app->make(Dispatcher::class), $app->runningUnitTests());
}
public function __construct(Repository $config, QueueManager $queue)
@ -39,25 +52,90 @@ class QueueTenancyBootstrapper implements TenancyBootstrapper
$this->setUpPayloadGenerator();
}
protected static function setUpJobListener($dispatcher)
protected static function setUpJobListener($dispatcher, $runningTests)
{
$dispatcher->listen(JobProcessing::class, function ($event) {
$tenantId = $event->job->payload()['tenant_id'] ?? null;
$previousTenant = null;
// The job is not tenant-aware
if (! $tenantId) {
return;
}
$dispatcher->listen(JobProcessing::class, function ($event) use (&$previousTenant) {
$previousTenant = tenant();
// Tenancy is already initialized for the tenant (e.g. dispatchNow was used)
if (tenancy()->initialized && tenant()->getTenantKey() === $tenantId) {
return;
}
// Tenancy was either not initialized, or initialized for a different tenant.
// Therefore, we initialize it for the correct tenant.
tenancy()->initialize(tenancy()->find($tenantId));
static::initializeTenancyForQueue($event->job->payload()['tenant_id'] ?? null);
});
if (version_compare(app()->version(), '8.64', '>=')) {
// JobRetryRequested only exists since Laravel 8.64
$dispatcher->listen(JobRetryRequested::class, function ($event) use (&$previousTenant) {
$previousTenant = tenant();
static::initializeTenancyForQueue($event->payload()['tenant_id'] ?? null);
});
}
// If we're running tests, we make sure to clean up after any artisan('queue:work') calls
$revertToPreviousState = function ($event) use (&$previousTenant, $runningTests) {
if ($runningTests) {
static::revertToPreviousState($event, $previousTenant);
}
};
$dispatcher->listen(JobProcessed::class, $revertToPreviousState); // artisan('queue:work') which succeeds
$dispatcher->listen(JobFailed::class, $revertToPreviousState); // artisan('queue:work') which fails
}
protected static function initializeTenancyForQueue($tenantId)
{
if (! $tenantId) {
// The job is not tenant-aware
if (tenancy()->initialized) {
// Tenancy was initialized, so we revert back to the central context
tenancy()->end();
}
return;
}
if (static::$forceRefresh) {
// Re-initialize tenancy between all jobs
if (tenancy()->initialized) {
tenancy()->end();
}
tenancy()->initialize(tenancy()->find($tenantId));
return;
}
if (tenancy()->initialized) {
// Tenancy is already initialized
if (tenant()->getTenantKey() === $tenantId) {
// It's initialized for the same tenant (e.g. dispatchNow was used, or the previous job also ran for this tenant)
return;
}
}
// Tenancy was either not initialized, or initialized for a different tenant.
// Therefore, we initialize it for the correct tenant.
tenancy()->initialize(tenancy()->find($tenantId));
}
protected static function revertToPreviousState($event, &$previousTenant)
{
$tenantId = $event->job->payload()['tenant_id'] ?? null;
// The job was not tenant-aware
if (! $tenantId) {
return;
}
// Revert back to the previous tenant
if (tenant() && $previousTenant && $previousTenant->isNot(tenant())) {
tenancy()->initialize($previousTenant);
}
// End tenancy
if (tenant() && (! $previousTenant)) {
tenancy()->end();
}
}
protected function setUpPayloadGenerator()

View file

@ -13,15 +13,16 @@ class CacheManager extends BaseCacheManager
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
$tags = [config('tenancy.cache.tag_base') . tenant()->getTenantKey()];
if ($method === 'tags') {
if (count($parameters) !== 1) {
throw new \Exception("Method tags() takes exactly 1 argument. {count($parameters)} passed.");
$count = count($parameters);
if ($count !== 1) {
throw new \Exception("Method tags() takes exactly 1 argument. $count passed.");
}
$names = $parameters[0];

View file

@ -24,8 +24,6 @@ class Install extends Command
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{

View file

@ -8,39 +8,31 @@ use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Database\Console\Migrations\MigrateCommand;
use Illuminate\Database\Migrations\Migrator;
use Stancl\Tenancy\Concerns\DealsWithMigrations;
use Stancl\Tenancy\Concerns\ExtendsLaravelCommand;
use Stancl\Tenancy\Concerns\HasATenantsOption;
use Stancl\Tenancy\Events\DatabaseMigrated;
use Stancl\Tenancy\Events\MigratingDatabase;
class Migrate extends MigrateCommand
{
use HasATenantsOption, DealsWithMigrations;
use HasATenantsOption, DealsWithMigrations, ExtendsLaravelCommand;
/**
* The console command description.
*
* @var string
*/
protected $description = 'Run migrations for tenant(s)';
/**
* Create a new command instance.
*
* @param Migrator $migrator
* @param Dispatcher $dispatcher
*/
protected static function getTenantCommandName(): string
{
return 'tenants:migrate';
}
public function __construct(Migrator $migrator, Dispatcher $dispatcher)
{
parent::__construct($migrator, $dispatcher);
$this->setName('tenants:migrate');
$this->specifyParameters();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
@ -55,7 +47,7 @@ class Migrate extends MigrateCommand
}
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) {
$this->line("Tenant: {$tenant['id']}");
$this->line("Tenant: {$tenant->getTenantKey()}");
event(new MigratingDatabase($tenant));

View file

@ -7,6 +7,7 @@ namespace Stancl\Tenancy\Commands;
use Illuminate\Console\Command;
use Stancl\Tenancy\Concerns\DealsWithMigrations;
use Stancl\Tenancy\Concerns\HasATenantsOption;
use Symfony\Component\Console\Input\InputOption;
final class MigrateFresh extends Command
{
@ -23,13 +24,13 @@ final class MigrateFresh extends Command
{
parent::__construct();
$this->addOption('--drop-views', null, InputOption::VALUE_NONE, 'Drop views along with tenant tables.', null);
$this->setName('tenants:migrate-fresh');
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
@ -37,6 +38,7 @@ final class MigrateFresh extends Command
$this->info('Dropping tables.');
$this->call('db:wipe', array_filter([
'--database' => 'tenant',
'--drop-views' => $this->option('drop-views'),
'--force' => true,
]));

View file

@ -7,13 +7,19 @@ namespace Stancl\Tenancy\Commands;
use Illuminate\Database\Console\Migrations\RollbackCommand;
use Illuminate\Database\Migrations\Migrator;
use Stancl\Tenancy\Concerns\DealsWithMigrations;
use Stancl\Tenancy\Concerns\ExtendsLaravelCommand;
use Stancl\Tenancy\Concerns\HasATenantsOption;
use Stancl\Tenancy\Events\DatabaseRolledBack;
use Stancl\Tenancy\Events\RollingBackDatabase;
class Rollback extends RollbackCommand
{
use HasATenantsOption, DealsWithMigrations;
use HasATenantsOption, DealsWithMigrations, ExtendsLaravelCommand;
protected static function getTenantCommandName(): string
{
return 'tenants:rollback';
}
/**
* The console command description.
@ -31,14 +37,11 @@ class Rollback extends RollbackCommand
{
parent::__construct($migrator);
$this->setName('tenants:rollback');
$this->specifyParameters();
$this->specifyTenantSignature();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
@ -53,7 +56,7 @@ class Rollback extends RollbackCommand
}
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) {
$this->line("Tenant: {$tenant['id']}");
$this->line("Tenant: {$tenant->getTenantKey()}");
event(new RollingBackDatabase($tenant));

View file

@ -27,14 +27,11 @@ class Run extends Command
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) {
$this->line("Tenant: {$tenant['id']}");
tenancy()->initialize($tenant);
$this->line("Tenant: {$tenant->getTenantKey()}");
$callback = function ($prefix = '') {
return function ($arguments, $argument) use ($prefix) {

View file

@ -35,8 +35,6 @@ class Seed extends SeedCommand
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
@ -51,7 +49,7 @@ class Seed extends SeedCommand
}
tenancy()->runForMultiple($this->option('tenants'), function ($tenant) {
$this->line("Tenant: {$tenant['id']}");
$this->line("Tenant: {$tenant->getTenantKey()}");
event(new SeedingDatabase($tenant));

View file

@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace Stancl\Tenancy\Commands;
use Illuminate\Console\Command;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Database\ConnectionResolverInterface;
use Illuminate\Database\Console\DumpCommand;
use Stancl\Tenancy\Contracts\Tenant;
use Symfony\Component\Console\Input\InputOption;
class TenantDump extends DumpCommand
{
public function __construct()
{
parent::__construct();
$this->setName('tenants:dump');
$this->specifyParameters();
}
public function handle(ConnectionResolverInterface $connections, Dispatcher $dispatcher): int
{
$this->tenant()->run(fn () => parent::handle($connections, $dispatcher));
return Command::SUCCESS;
}
public function tenant(): Tenant
{
$tenant = $this->option('tenant')
?? tenant()
?? $this->ask('What tenant do you want to dump the schema for?')
?? tenancy()->query()->first();
if (! $tenant instanceof Tenant) {
$tenant = tenancy()->find($tenant);
}
throw_if(! $tenant, 'Could not identify the tenant to use for dumping the schema.');
return $tenant;
}
protected function getOptions(): array
{
return array_merge([
['tenant', null, InputOption::VALUE_OPTIONAL, '', null],
], parent::getOptions());
}
}

View file

@ -25,8 +25,6 @@ class TenantList extends Command
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
@ -36,9 +34,9 @@ class TenantList extends Command
->cursor()
->each(function (Tenant $tenant) {
if ($tenant->domains) {
$this->line("[Tenant] id: {$tenant['id']} @ " . implode('; ', $tenant->domains->pluck('domain')->toArray() ?? []));
$this->line("[Tenant] {$tenant->getTenantKeyName()}: {$tenant->getTenantKey()} @ " . implode('; ', $tenant->domains->pluck('domain')->toArray() ?? []));
} else {
$this->line("[Tenant] id: {$tenant['id']}");
$this->line("[Tenant] {$tenant->getTenantKeyName()}: {$tenant->getTenantKey()}");
}
});
}

View file

@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace Stancl\Tenancy\Concerns;
trait ExtendsLaravelCommand
{
protected function specifyTenantSignature(): void
{
$this->specifyParameters();
}
public function getName(): ?string
{
return static::getTenantCommandName();
}
public static function getDefaultName(): ?string
{
return static::getTenantCommandName();
}
abstract protected static function getTenantCommandName(): string;
}

View file

@ -12,7 +12,7 @@ trait HasATenantsOption
protected function getOptions()
{
return array_merge([
['tenants', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_OPTIONAL, '', null],
['tenants', null, InputOption::VALUE_IS_ARRAY|InputOption::VALUE_OPTIONAL, '', null],
], parent::getOptions());
}

View file

@ -20,18 +20,11 @@ interface TenantDatabaseManager
/**
* Does a database exist.
*
* @param string $name
* @return bool
*/
public function databaseExists(string $name): bool;
/**
* Make a DB connection config array.
*
* @param array $baseConfig
* @param string $databaseName
* @return array
*/
public function makeConnectionConfig(array $baseConfig, string $databaseName): array;
@ -39,9 +32,6 @@ interface TenantDatabaseManager
* Set the DB connection that should be used by the tenant database manager.
*
* @throws NoConnectionSetException
*
* @param string $connection
* @return void
*/
public function setConnection(string $connection): void;
}

View file

@ -11,9 +11,6 @@ trait TenantRun
/**
* Run a callback in this tenant's context.
* Atomic, safely reverts to previous context.
*
* @param callable $callback
* @return mixed
*/
public function run(callable $callback)
{

View file

@ -7,10 +7,12 @@ namespace Stancl\Tenancy\Database;
use Illuminate\Config\Repository;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Database\DatabaseManager as BaseDatabaseManager;
use Stancl\Tenancy\Contracts\ManagesDatabaseUsers;
use Stancl\Tenancy\Contracts\TenantCannotBeCreatedException;
use Stancl\Tenancy\Contracts\TenantWithDatabase;
use Stancl\Tenancy\Exceptions\DatabaseManagerNotRegisteredException;
use Stancl\Tenancy\Exceptions\TenantDatabaseAlreadyExistsException;
use Stancl\Tenancy\Exceptions\TenantDatabaseUserAlreadyExistsException;
/**
* @internal Class is subject to breaking changes in minor and patch versions.
@ -38,7 +40,7 @@ class DatabaseManager
*/
public function connectToTenant(TenantWithDatabase $tenant)
{
$this->database->purge('tenant');
$this->purgeTenantConnection();
$this->createTenantConnection($tenant);
$this->setDefaultConnection('tenant');
}
@ -48,10 +50,7 @@ class DatabaseManager
*/
public function reconnectToCentral()
{
if (tenancy()->initialized) {
$this->database->purge('tenant');
}
$this->purgeTenantConnection();
$this->setDefaultConnection($this->config->get('tenancy.database.central_connection'));
}
@ -60,7 +59,7 @@ class DatabaseManager
*/
public function setDefaultConnection(string $connection)
{
$this->app['config']['database.default'] = $connection;
$this->config['database.default'] = $connection;
$this->database->setDefaultConnection($connection);
}
@ -69,7 +68,19 @@ class DatabaseManager
*/
public function createTenantConnection(TenantWithDatabase $tenant)
{
$this->app['config']['database.connections.tenant'] = $tenant->database()->connection();
$this->config['database.connections.tenant'] = $tenant->database()->connection();
}
/**
* Purge the tenant database connection.
*/
public function purgeTenantConnection()
{
if (array_key_exists('tenant', $this->database->getConnections())) {
$this->database->purge('tenant');
}
unset($this->config['database.connections.tenant']);
}
/**
@ -81,8 +92,14 @@ class DatabaseManager
*/
public function ensureTenantCanBeCreated(TenantWithDatabase $tenant): void
{
if ($tenant->database()->manager()->databaseExists($database = $tenant->database()->getName())) {
$manager = $tenant->database()->manager();
if ($manager->databaseExists($database = $tenant->database()->getName())) {
throw new TenantDatabaseAlreadyExistsException($database);
}
if ($manager instanceof ManagesDatabaseUsers && $manager->userExists($username = $tenant->database()->getUsername())) {
throw new TenantDatabaseUserAlreadyExistsException($username);
}
}
}

View file

@ -22,10 +22,15 @@ class ImpersonationToken extends Model
use CentralConnection;
protected $guarded = [];
public $timestamps = false;
protected $primaryKey = 'token';
public $incrementing = false;
protected $table = 'tenant_user_impersonation_tokens';
protected $dates = [
'created_at',
];

View file

@ -29,7 +29,9 @@ class Tenant extends Model implements Contracts\Tenant
Concerns\InvalidatesResolverCache;
protected $table = 'tenants';
protected $primaryKey = 'id';
protected $guarded = [];
public function getTenantKeyName(): string

View file

@ -80,8 +80,6 @@ class DatabaseConfig
/**
* Generate DB name, username & password and write them to the tenant model.
*
* @return void
*/
public function makeCredentials(): void
{
@ -113,7 +111,8 @@ class DatabaseConfig
$templateConnection = config("database.connections.{$template}");
return $this->manager()->makeConnectionConfig(
array_merge($templateConnection, $this->tenantConfig()), $this->getName()
array_merge($templateConnection, $this->tenantConfig()),
$this->getName()
);
}

View file

@ -9,7 +9,7 @@ use Facade\IgnitionContracts\ProvidesSolution;
use Facade\IgnitionContracts\Solution;
use Stancl\Tenancy\Contracts\TenantCouldNotBeIdentifiedException;
// todo: in v3 this should be suffixed with Exception
// todo: in v4 this should be suffixed with Exception
class TenantCouldNotBeIdentifiedById extends TenantCouldNotBeIdentifiedException implements ProvidesSolution
{
public function __construct($tenant_id)

View file

@ -23,11 +23,17 @@ class UniversalRoutes implements Feature
public function bootstrap(Tenancy $tenancy): void
{
foreach (static::$identificationMiddlewares as $middleware) {
$middleware::$onFail = function ($exception, $request, $next) {
$originalOnFail = $middleware::$onFail;
$middleware::$onFail = function ($exception, $request, $next) use ($originalOnFail) {
if (static::routeHasMiddleware($request->route(), static::$middlewareGroup)) {
return $next($request);
}
if ($originalOnFail) {
return $originalOnFail($exception, $request, $next);
}
throw $exception;
};
}
@ -40,7 +46,7 @@ class UniversalRoutes implements Feature
}
// Loop one level deep and check if the route's middleware
// groups have the searhced middleware group inside them
// 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)) {

View file

@ -33,7 +33,6 @@ class UserImpersonation implements Feature
*
* @param string|ImpersonationToken $token
* @param int $ttl
* @return RedirectResponse
*/
public static function makeResponse($token, int $ttl = null): RedirectResponse
{

View file

@ -36,8 +36,8 @@ class CreateDatabase implements ShouldQueue
return false;
}
$databaseManager->ensureTenantCanBeCreated($this->tenant);
$this->tenant->database()->makeCredentials();
$databaseManager->ensureTenantCanBeCreated($this->tenant);
$this->tenant->database()->manager()->createDatabase($this->tenant);
event(new DatabaseCreated($this->tenant));

View file

@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace Stancl\Tenancy\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Stancl\Tenancy\Contracts\TenantWithDatabase;
class DeleteDomains
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/** @var TenantWithDatabase */
protected $tenant;
public function __construct(TenantWithDatabase $tenant)
{
$this->tenant = $tenant;
}
public function handle()
{
$this->tenant->domains->each->delete();
}
}

View file

@ -48,8 +48,7 @@ class UpdateSyncedResource extends QueueableListener
protected function updateResourceInCentralDatabaseAndGetTenants($event, $syncedAttributes)
{
/** @var Model|SyncMaster $centralModel */
$centralModel = $event->model->getCentralModelName()
::where($event->model->getGlobalIdentifierKeyName(), $event->model->getGlobalIdentifierKey())
$centralModel = $event->model->getCentralModelName()::where($event->model->getGlobalIdentifierKeyName(), $event->model->getGlobalIdentifierKey())
->first();
// We disable events for this call, to avoid triggering this event & listener again.

View file

@ -5,10 +5,10 @@ declare(strict_types=1);
namespace Stancl\Tenancy\Middleware;
use Closure;
use Illuminate\Foundation\Http\Exceptions\MaintenanceModeException;
use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode;
use Stancl\Tenancy\Exceptions\TenancyNotInitializedException;
use Symfony\Component\HttpFoundation\IpUtils;
use Symfony\Component\HttpKernel\Exception\HttpException;
class CheckTenantForMaintenanceMode extends CheckForMaintenanceMode
{
@ -29,7 +29,12 @@ class CheckTenantForMaintenanceMode extends CheckForMaintenanceMode
return $next($request);
}
throw new MaintenanceModeException($data['time'], $data['retry'], $data['message']);
throw new HttpException(
503,
'Service Unavailable',
null,
isset($data['retry']) ? ['Retry-After' => $data['retry']] : []
);
}
return $next($request);

View file

@ -29,13 +29,13 @@ class InitializeTenancyByDomain extends IdentificationMiddleware
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $this->initializeTenancy(
$request, $next, $request->getHost()
$request,
$next,
$request->getHost()
);
}
}

View file

@ -13,8 +13,6 @@ class InitializeTenancyByDomainOrSubdomain
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{

View file

@ -38,7 +38,9 @@ class InitializeTenancyByPath extends IdentificationMiddleware
// simply injected into some route controller action.
if ($route->parameterNames()[0] === PathTenantResolver::$tenantParameterName) {
return $this->initializeTenancy(
$request, $next, $route
$request,
$next,
$route
);
} else {
throw new RouteIsMissingTenantParameterException;

View file

@ -36,8 +36,6 @@ class InitializeTenancyByRequestData extends IdentificationMiddleware
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{

View file

@ -28,8 +28,6 @@ class InitializeTenancyBySubdomain extends InitializeTenancyByDomain
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{

View file

@ -75,7 +75,6 @@ abstract class CachedTenantResolver implements TenantResolver
/**
* Get all the arg combinations for resolve() that can be used to find this tenant.
*
* @param Tenant $tenant
* @return array[]
*/
abstract public function getArgsForTenant(Tenant $tenant): array;

View file

@ -27,7 +27,6 @@ class Tenancy
/**
* Initializes the tenant.
* @param Tenant|int|string $tenant
* @return void
*/
public function initialize($tenant): void
{
@ -66,10 +65,10 @@ class Tenancy
return;
}
$this->initialized = false;
event(new Events\TenancyEnded($this));
$this->initialized = false;
$this->tenant = null;
}
@ -106,9 +105,6 @@ class Tenancy
/**
* Run a callback in the central context.
* Atomic, safely reverts to previous context.
*
* @param callable $callback
* @return mixed
*/
public function central(callable $callback)
{
@ -132,7 +128,6 @@ class Tenancy
* More performant than running $tenant->run() one by one.
*
* @param Tenant[]|\Traversable|string[]|null $tenants
* @param callable $callback
* @return void
*/
public function runForMultiple($tenants, callable $callback)

View file

@ -7,6 +7,7 @@ namespace Stancl\Tenancy;
use Illuminate\Cache\CacheManager;
use Illuminate\Support\ServiceProvider;
use Stancl\Tenancy\Bootstrappers\FilesystemTenancyBootstrapper;
use Stancl\Tenancy\Contracts\Domain;
use Stancl\Tenancy\Contracts\Tenant;
use Stancl\Tenancy\Resolvers\DomainTenantResolver;
@ -14,8 +15,6 @@ class TenancyServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register(): void
{
@ -75,8 +74,6 @@ class TenancyServiceProvider extends ServiceProvider
/**
* Bootstrap services.
*
* @return void
*/
public function boot(): void
{
@ -88,6 +85,7 @@ class TenancyServiceProvider extends ServiceProvider
Commands\Migrate::class,
Commands\Rollback::class,
Commands\TenantList::class,
Commands\TenantDump::class,
Commands\MigrateFresh::class,
]);

View file

@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace Stancl\Tenancy\TenantDatabaseManagers;
use Illuminate\Database\Connection;
use Illuminate\Support\Facades\DB;
use Stancl\Tenancy\Contracts\TenantDatabaseManager;
use Stancl\Tenancy\Contracts\TenantWithDatabase;
use Stancl\Tenancy\Exceptions\NoConnectionSetException;
class MicrosoftSQLDatabaseManager implements TenantDatabaseManager
{
/** @var string */
protected $connection;
protected function database(): Connection
{
if ($this->connection === null) {
throw new NoConnectionSetException(static::class);
}
return DB::connection($this->connection);
}
public function setConnection(string $connection): void
{
$this->connection = $connection;
}
public function createDatabase(TenantWithDatabase $tenant): bool
{
$database = $tenant->database()->getName();
$charset = $this->database()->getConfig('charset');
$collation = $this->database()->getConfig('collation');
return $this->database()->statement("CREATE DATABASE [{$database}]");
}
public function deleteDatabase(TenantWithDatabase $tenant): bool
{
return $this->database()->statement("DROP DATABASE [{$tenant->database()->getName()}]");
}
public function databaseExists(string $name): bool
{
return (bool) $this->database()->select("SELECT name FROM master.sys.databases WHERE name = '$name'");
}
public function makeConnectionConfig(array $baseConfig, string $databaseName): array
{
$baseConfig['database'] = $databaseName;
return $baseConfig;
}
}

View file

@ -7,7 +7,6 @@ namespace Stancl\Tenancy\TenantDatabaseManagers;
use Stancl\Tenancy\Concerns\CreatesDatabaseUsers;
use Stancl\Tenancy\Contracts\ManagesDatabaseUsers;
use Stancl\Tenancy\DatabaseConfig;
use Stancl\Tenancy\Exceptions\TenantDatabaseUserAlreadyExistsException;
class PermissionControlledMySQLDatabaseManager extends MySQLDatabaseManager implements ManagesDatabaseUsers
{
@ -26,10 +25,6 @@ class PermissionControlledMySQLDatabaseManager extends MySQLDatabaseManager impl
$hostname = $databaseConfig->connection()['host'];
$password = $databaseConfig->getPassword();
if ($this->userExists($username)) {
throw new TenantDatabaseUserAlreadyExistsException($username);
}
$this->database()->statement("CREATE USER `{$username}`@`%` IDENTIFIED BY '{$password}'");
$grants = implode(', ', static::$grants);

View file

@ -46,7 +46,11 @@ class PostgreSQLSchemaManager implements TenantDatabaseManager
public function makeConnectionConfig(array $baseConfig, string $databaseName): array
{
$baseConfig['schema'] = $databaseName;
if (version_compare(app()->version(), '9.0', '>=')) {
$baseConfig['search_path'] = $databaseName;
} else {
$baseConfig['schema'] = $databaseName;
}
return $baseConfig;
}