CreateTenant::handle()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 27
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 15
c 1
b 0
f 0
nc 3
nop 0
dl 0
loc 27
rs 9.7666
1
<?php
2
3
namespace App\Console\Commands;
4
5
use App\Models\Tenant;
6
use Illuminate\Console\Command;
7
use Illuminate\Support\Facades\DB;
8
use Symfony\Component\Console\Exception\RuntimeException;
9
10
class CreateTenant extends Command
11
{
12
    /**
13
     * The name and signature of the console command.
14
     *
15
     * @var string
16
     */
17
    protected $signature = 'tenant:create {subdomain : tenant subdomain}';
18
19
    /**
20
     * The console command description.
21
     *
22
     * @var string
23
     */
24
    protected $description = 'Creates new tenant with new database';
25
26
    /**
27
     * Create a new command instance.
28
     *
29
     * @return void
30
     */
31
    public function __construct()
32
    {
33
        parent::__construct();
34
    }
35
36
    /**
37
     * Execute the console command.
38
     *
39
     * @return mixed
40
     */
41
    public function handle()
42
    {
43
        $subdomain = $this->argument('subdomain');
44
45
        if (!ctype_alnum($subdomain)) {
46
            throw new RuntimeException('Subdomain can consist of alphanum chars only.');
47
        }
48
49
        $num = Tenant::where('subdomain', $subdomain)->count();
50
51
        if ($num) {
52
            throw new RuntimeException('Tenant with subdomain \''.$subdomain.'\' already exists.');
0 ignored issues
show
Bug introduced by
Are you sure $subdomain of type array|null|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

52
            throw new RuntimeException('Tenant with subdomain \''./** @scrutinizer ignore-type */ $subdomain.'\' already exists.');
Loading history...
53
        }
54
55
        $tenant = new Tenant();
56
        $tenant->subdomain = $subdomain;
57
        $tenant->save();
58
59
        $databaseName = 'tenant_'.$tenant->id;
60
        DB::connection('tenant')->statement('CREATE DATABASE '.$databaseName);
61
62
        $this->callSilent('tenant:migrate', [
63
            'tenantId' => $tenant->id,
64
        ]);
65
66
        $this->info('Created tenant with subdomain \''.$subdomain.'\' and ID '.$tenant->id.'.');
67
        $this->info('Database tables has been migrated.');
68
    }
69
}
70