Migration::null()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 5
rs 10
1
<?php
2
3
namespace Erykai\Migration;
4
5
class Migration extends Resource
6
{
7
    public function table(string $name): void
8
    {
9
        $this->setTable($name);
10
    }
11
12
    public function column(string $name): static
13
    {
14
        $this->setNull(" NOT NULL");
15
        $this->setColumns($name);
16
        return $this;
17
    }
18
19
    public function type(string $name): static
20
    {
21
        $this->setTypes($name);
22
        return $this;
23
    }
24
25
    public function null(): static
26
    {
27
        $key = count($this->null) - 1;
28
        $this->null[$key] = "";
29
        return $this;
30
    }
31
32
    public function default(bool|string $default = false): static
33
    {
34
        $this->setDefault($default);
35
        return $this;
36
    }
37
38
    public function primary(string $nameColumn)
39
    {
40
        $query = "ALTER TABLE `{$this->getTable()}` ADD PRIMARY KEY (`$nameColumn`)";
41
        $this->conn->query($query);
42
    }
43
44
    public function autoIncrement(string $nameColumn)
45
    {
46
        $query = "ALTER TABLE `{$this->getTable()}` MODIFY `$nameColumn` int(11) NOT NULL AUTO_INCREMENT;";
47
        $this->conn->query($query);
48
        $this->conn->query("COMMIT;");
49
    }
50
51
    public function addKey(string $nameKey, string $nameColumn, string $tableReference, string $idTableReference)
52
    {
53
        $this->setKey($nameKey);
54
        $this->conn->query("ALTER TABLE `{$this->getTable()}` ADD KEY `{$this->getKey()}` (`$nameColumn`);");
55
        $this->conn->query("ALTER TABLE `{$this->getTable()}` ADD CONSTRAINT `{$this->getKey()}` FOREIGN KEY (`$nameColumn`) REFERENCES `$tableReference` (`$idTableReference`) ON DELETE CASCADE ON UPDATE CASCADE;");
56
    }
57
58
59
    public function save(): void
60
    {
61
        $query = "(";
62
        $default = null;
63
        foreach ($this->getColumns() as $key => $column) {
64
            if ($this->getDefault()[$key]) {
65
                $default = ' DEFAULT ' . $this->getDefault()[$key];
66
            }
67
            $query .= "`$column` {$this->getTypes()[$key]}$default{$this->getNull()[$key]},";
68
        }
69
        $query = rtrim($query, ",");
70
        $query .= ") ";
71
        $query .= "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;";
72
        $data = "CREATE TABLE {$this->getTable()} $query";
73
        $this->conn->query($data);
74
    }
75
}