TableTrait::dropIndexesSql()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 15
rs 10
1
<?php
2
3
/**
4
 * Quantum PHP Framework
5
 *
6
 * An open source software development framework for PHP
7
 *
8
 * @package Quantum
9
 * @author Arman Ag. <[email protected]>
10
 * @copyright Copyright (c) 2018 Softberg LLC (https://softberg.org)
11
 * @link http://quantum.softberg.org/
12
 * @since 3.0.0
13
 */
14
15
namespace Quantum\Libraries\Database\Traits;
16
17
use Quantum\Libraries\Database\Schemas\Column;
18
use Quantum\Libraries\Database\Enums\Key;
19
20
/**
21
 * Trait TableTrait
22
 * @package Quantum\Libraries\Database
23
 */
24
trait TableTrait
25
{
26
    /**
27
     * Generates create table statement
28
     * @return string
29
     */
30
    protected function createTableSql(): string
31
    {
32
        $tableSchema = array_filter([$this->columnsSql(), $this->indexesSql()]);
33
        $sql = '';
34
35
        if ($tableSchema !== []) {
36
            $sql = 'CREATE TABLE `' . $this->name . '` (';
37
            $sql .= implode(', ', $tableSchema);
38
            $sql .= ');';
39
        }
40
41
        return $sql;
42
    }
43
44
    /**
45
     * Generates alter table statement
46
     * @return string
47
     */
48
    protected function alterTableSql(): string
49
    {
50
        $tableSchema = array_filter([$this->columnsSql(), $this->indexesSql(), $this->dropIndexesSql()]);
51
        $sql = '';
52
53
        if ($tableSchema !== []) {
54
            $sql = 'ALTER TABLE `' . $this->name . '` ';
55
            $sql .= implode(', ', $tableSchema);
56
            $sql .= ';';
57
        }
58
59
        return $sql;
60
    }
61
62
    /**
63
     * Prepares rename table statement
64
     * @return string
65
     */
66
    protected function renameTableSql(): string
67
    {
68
        return 'RENAME TABLE `' . $this->name . '` TO `' . $this->newName . '`;';
69
    }
70
71
    /**
72
     * Prepares drop table statement
73
     * @return string
74
     */
75
    protected function dropTableSql(): string
76
    {
77
        return 'DROP TABLE `' . $this->name . '`';
78
    }
79
80
    /**
81
     * Prepares columns statements for table
82
     * @return string
83
     */
84
    protected function columnsSql(): string
85
    {
86
        $sql = '';
87
88
        if ($this->columns) {
89
            $columns = [];
90
91
            foreach ($this->columns as $entry) {
92
                $columnString = '';
93
94
                if ($entry['action'] != Column::ADD_INDEX && $entry['action'] != Column::DROP_INDEX) {
95
                    $columnString .= ($entry['action'] ? $entry['action'] . ' COLUMN ' : '');
96
                    $columnString .= $this->composeColumn($entry['column'], $entry['action']);
97
                }
98
99
                if ($entry['column']->get('indexKey')) {
100
                    $this->indexKeys[$entry['column']->get('indexKey')][] = [
0 ignored issues
show
Bug Best Practice introduced by
The property indexKeys does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
101
                        'columnName' => $entry['column']->get('name'),
102
                        'indexName' => $entry['column']->get('indexName'),
103
                    ];
104
                }
105
106
                if ($entry['column']->get('indexDrop')) {
107
                    $this->droppedIndexKeys[] = $entry['column']->get('indexDrop');
0 ignored issues
show
Bug Best Practice introduced by
The property droppedIndexKeys does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
108
                }
109
110
                if ($columnString !== '' && $columnString !== '0') {
111
                    $columns[] = $columnString;
112
                }
113
            }
114
115
            $sql = implode(', ', $columns);
116
        }
117
118
        return $sql;
119
    }
120
121
    /**
122
     * Composes the column
123
     * @param Column $column
124
     * @param string|null $action
125
     * @return string
126
     */
127
    protected function composeColumn(Column $column, ?string $action = null): string
128
    {
129
        return
130
            $this->columnAttrSql($column->get(Column::NAME), '`', '`') .
131
            $this->columnAttrSql($column->get(Column::NEW_NAME), ' TO `', '`') .
132
            $this->columnAttrSql($column->get(Column::TYPE), ' ') .
133
            $this->columnAttrSql($column->get(Column::CONSTRAINT), '(', ')') .
134
            $this->columnAttrSql($column->get(Column::ATTRIBUTE), ' ') .
135
            $this->columnAttrSql($column->get(Column::NULLABLE, $action), ' ') .
136
            $this->columnAttrSql($column->get(Column::DEFAULT), ' DEFAULT ' . ($column->defaultQuoted() ? '\'' : ''), ($column->defaultQuoted() ? '\'' : '')) .
137
            $this->columnAttrSql($column->get(Column::COMMENT), ' COMMENT \'', '\'') .
138
            $this->columnAttrSql($column->get(Column::AFTER), ' AFTER `', '`') .
139
            $this->columnAttrSql($column->get(Column::AUTO_INCREMENT), ' ');
140
    }
141
142
    /**
143
     * Prepares column attributes
144
     * @param mixed $definition
145
     * @param string $before
146
     * @param string $after
147
     * @return string
148
     */
149
    protected function columnAttrSql($definition, string $before = '', string $after = ''): string
150
    {
151
        $sql = '';
152
153
        if (!is_null($definition)) {
154
155
            $sql .= $before . (is_array($definition) ? ("'" . implode("', '", $definition) . "'") : $definition) . $after;
156
        }
157
158
        return $sql;
159
    }
160
161
    /**
162
     * Prepares statement for primary key
163
     * @return string
164
     */
165
    protected function primaryKeysSql(): string
166
    {
167
        $sql = '';
168
169
        if (isset($this->indexKeys['primary'])) {
170
            $sql .= ($this->action == self::ALTER ? 'ADD ' : '');
0 ignored issues
show
Bug introduced by
The constant Quantum\Libraries\Databa...raits\TableTrait::ALTER was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
171
172
            $sql .= 'PRIMARY KEY (';
173
174
            foreach ($this->indexKeys['primary'] as $key => $primaryKey) {
175
                $sql .= '`' . $primaryKey['columnName'] . '`';
176
                $sql .= (array_key_last($this->indexKeys['primary']) != $key ? ', ' : '');
177
            }
178
179
            $sql .= ')';
180
        }
181
182
        return $sql;
183
    }
184
185
    /**
186
     * Prepares statement for index keys
187
     * @param string $type
188
     * @return string
189
     */
190
    protected function indexKeysSql(string $type): string
191
    {
192
        $sql = '';
193
194
        if (isset($this->indexKeys[$type])) {
195
            $indexes = [];
196
197
            foreach ($this->indexKeys[$type] as $indexKey) {
198
                $indexString = ($this->action == self::ALTER ? 'ADD ' : '');
0 ignored issues
show
Bug introduced by
The constant Quantum\Libraries\Databa...raits\TableTrait::ALTER was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
199
                $indexString .= strtoupper($type);
200
                $indexString .= ($indexKey['indexName'] ? ' `' . $indexKey['indexName'] . '`' : '');
201
                $indexString .= ' (`' . $indexKey['columnName'] . '`)';
202
203
                $indexes[] = $indexString;
204
            }
205
206
            $sql = implode(', ', $indexes);
207
        }
208
209
        return $sql;
210
    }
211
212
    /**
213
     * Builds a complete statement for index keys
214
     * @return string
215
     */
216
    protected function indexesSql(): string
217
    {
218
        $indexes = [
219
            $this->primaryKeysSql(),
220
            $this->indexKeysSql(Key::INDEX),
221
            $this->indexKeysSql(Key::UNIQUE),
222
            $this->indexKeysSql(Key::FULLTEXT),
223
            $this->indexKeysSql(Key::SPATIAL),
224
        ];
225
226
        return implode(', ', array_filter($indexes));
227
    }
228
229
    /**
230
     * Builds a statement for drop indexes
231
     * @return string
232
     */
233
    protected function dropIndexesSql(): string
234
    {
235
        $sql = '';
236
237
        if (!empty($this->droppedIndexKeys)) {
238
            $indexes = [];
239
240
            foreach ($this->droppedIndexKeys as $index) {
241
                $indexes[] = 'DROP INDEX `' . $index . '`';
242
            }
243
244
            $sql .= implode(', ', $indexes);
245
        }
246
247
        return $sql;
248
    }
249
}
250