Passed
Push — master ( 3d397a...3f0190 )
by Andrey
12:15
created

CreateRolesAndPermissionsTables::dropTables()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
use Illuminate\Database\Schema\Blueprint;
4
5
class CreateRolesAndPermissionsTables extends BaseMigration
6
{
7
    public function up()
8
    {
9
        $this->createTable($this->roles);
10
        $this->createTable($this->permissions);
11
12
        $this->createPivot($this->user_roles, $this->users, $this->roles, 'user_id', 'role_id');
13
        $this->createPivot($this->role_permissions, $this->roles, $this->permissions, 'role_id', 'permission_id');
14
    }
15
16
    public function down()
17
    {
18
        $this->schema()->disableForeignKeyConstraints();
19
20
        $this->dropTables($this->role_permissions, $this->user_roles, $this->permissions, $this->roles);
21
22
        $this->schema()->enableForeignKeyConstraints();
23
    }
24
25
    protected function createTable(string $table)
26
    {
27
        $this->create($table, function (Blueprint $table) {
28
            $table->bigIncrements('id');
29
            $table->string('name')->unique();
30
            $table->timestamps();
31
        });
32
    }
33
34
    protected function createPivot(string $table, string $first_table, string $second_table, string $first_key, string $second_key)
35
    {
36
        $this->create($table, function (Blueprint $table) use ($first_table, $second_table, $first_key, $second_key) {
37
            $table->unsignedBigInteger($first_key);
38
            $table->unsignedBigInteger($second_key);
39
40
            $table->foreign($first_key)->references('id')->on($first_table)->onDelete('cascade');
41
            $table->foreign($second_key)->references('id')->on($second_table)->onDelete('cascade');
42
43
            $table->primary([$first_key, $second_key]);
44
        });
45
    }
46
47
    protected function dropTables(...$tables)
48
    {
49
        foreach ($tables as $table) {
50
            $this->drop($table);
51
        }
52
    }
53
}
54