1
0
Fork 0
mirror of https://github.com/archtechx/tenancy.git synced 2026-02-05 05:44:04 +00:00

Get RLS models from a temporary tenant

This commit is contained in:
lukinovec 2023-06-05 12:03:48 +02:00
parent 7c7680baf6
commit 983e4c1f84

View file

@ -16,16 +16,26 @@ class CreateRLSPoliciesForTenantTables extends Command
public function handle(): int public function handle(): int
{ {
foreach (config('tenancy.models.rls') as $modelClass) { foreach ($this->rlsModels() as $model) {
/** @var Model $model */
$model = new $modelClass;
DB::transaction(fn () => $this->makeModelUseRls($model)); DB::transaction(fn () => $this->makeModelUseRls($model));
} }
return Command::SUCCESS; return Command::SUCCESS;
} }
protected function rlsModels(): array
{
tenancy()->initialize($tenant = tenancy()->model()::create());
$rlsTables = array_map(fn ($table) => $table->tablename, Schema::getAllTables());
tenancy()->end();
$tenant->delete();
return array_filter(array_map(fn ($table) => $this->getModelFromTable($table), $rlsTables));
}
protected function makeModelUseRls(Model $model): void protected function makeModelUseRls(Model $model): void
{ {
$table = $model->getTable(); $table = $model->getTable();
@ -82,4 +92,19 @@ class CreateRLSPoliciesForTenantTables extends Command
DB::statement("ALTER TABLE {$table} ENABLE ROW LEVEL SECURITY"); DB::statement("ALTER TABLE {$table} ENABLE ROW LEVEL SECURITY");
DB::statement("ALTER TABLE {$table} FORCE ROW LEVEL SECURITY"); DB::statement("ALTER TABLE {$table} FORCE ROW LEVEL SECURITY");
} }
protected function getModelFromTable(string $table): Model|null
{
foreach(get_declared_classes() as $class) {
if(is_subclass_of($class, Model::class)) {
$model = new $class;
if ($model->getTable() === $table) {
return $model;
}
}
}
return null;
}
} }