Completed
Push — master ( 824ab5...b7a7bb )
by Arman
16s queued 13s
created

TableBuilder::columnAttrSql()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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