From 983e4c1f843f149fe1cedfd1835ecb94992716ef Mon Sep 17 00:00:00 2001 From: lukinovec Date: Mon, 5 Jun 2023 12:03:48 +0200 Subject: [PATCH] Get RLS models from a temporary tenant --- .../CreateRLSPoliciesForTenantTables.php | 33 ++++++++++++++++--- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/src/Commands/CreateRLSPoliciesForTenantTables.php b/src/Commands/CreateRLSPoliciesForTenantTables.php index 6270c256..0ae4f1b6 100644 --- a/src/Commands/CreateRLSPoliciesForTenantTables.php +++ b/src/Commands/CreateRLSPoliciesForTenantTables.php @@ -16,16 +16,26 @@ class CreateRLSPoliciesForTenantTables extends Command public function handle(): int { - foreach (config('tenancy.models.rls') as $modelClass) { - /** @var Model $model */ - $model = new $modelClass; - + foreach ($this->rlsModels() as $model) { DB::transaction(fn () => $this->makeModelUseRls($model)); } 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 { $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} 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; + } }