akubiczek /
applicake-backend
| 1 | <?php |
||
| 2 | |||
| 3 | namespace App\Console\Commands; |
||
| 4 | |||
| 5 | use App\Models\Tenant; |
||
| 6 | use App\Services\TenantManager; |
||
| 7 | use Illuminate\Console\Command; |
||
| 8 | use Symfony\Component\Console\Exception\RuntimeException; |
||
| 9 | |||
| 10 | class TenantMigrate extends Command |
||
| 11 | { |
||
| 12 | protected $signature = 'tenant:migrate {tenantId?}'; |
||
| 13 | |||
| 14 | protected $description = 'Run tenant migrations for provided tenant or for all registered tenants'; |
||
| 15 | |||
| 16 | protected $tenantManager; |
||
| 17 | |||
| 18 | protected $migrator; |
||
| 19 | |||
| 20 | public function __construct(TenantManager $tenantManager) |
||
| 21 | { |
||
| 22 | parent::__construct(); |
||
| 23 | |||
| 24 | $this->tenantManager = $tenantManager; |
||
| 25 | $this->migrator = app('migrator'); |
||
| 26 | } |
||
| 27 | |||
| 28 | public function handle() |
||
| 29 | { |
||
| 30 | $tenantId = $this->argument('tenantId'); |
||
| 31 | |||
| 32 | if ($tenantId) { |
||
| 33 | $tenant = Tenant::find($tenantId); |
||
| 34 | if (!$tenant) { |
||
| 35 | throw new RuntimeException('Tenant with ID = '.$tenantId.' does not exist.'); |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 36 | } |
||
| 37 | |||
| 38 | $this->tenantManager->setTenant($tenant); |
||
| 39 | \DB::purge('tenant'); |
||
| 40 | $this->migrate(); |
||
| 41 | |||
| 42 | return; |
||
| 43 | } |
||
| 44 | |||
| 45 | if (!$tenantId && $this->confirm('Do you wish to run migration for ALL tenants?')) { |
||
| 46 | $tenants = Tenant::all(); |
||
| 47 | |||
| 48 | foreach ($tenants as $tenant) { |
||
| 49 | $this->tenantManager->setTenant($tenant); |
||
| 50 | \DB::purge('tenant'); |
||
| 51 | $this->migrate(); |
||
| 52 | } |
||
| 53 | |||
| 54 | return; |
||
| 55 | } |
||
| 56 | } |
||
| 57 | |||
| 58 | private function migrate() |
||
| 59 | { |
||
| 60 | $this->prepareDatabase(); |
||
| 61 | $this->migrator->run(database_path('migrations/tenants'), []); |
||
| 62 | } |
||
| 63 | |||
| 64 | protected function prepareDatabase() |
||
| 65 | { |
||
| 66 | $this->migrator->setConnection('tenant'); |
||
| 67 | |||
| 68 | if (!$this->migrator->repositoryExists()) { |
||
| 69 | $this->call('migrate:install'); |
||
| 70 | } |
||
| 71 | } |
||
| 72 | } |
||
| 73 |