TenantMigrate::handle()   A
last analyzed

Complexity

Conditions 6
Paths 5

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 6
eloc 16
c 1
b 0
f 1
nc 5
nop 0
dl 0
loc 27
rs 9.1111
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
Are you sure $tenantId of type array|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

35
                throw new RuntimeException('Tenant with ID = './** @scrutinizer ignore-type */ $tenantId.' does not exist.');
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