Completed
Push — master ( f6579a...8994b4 )
by Arman
16s queued 13s
created

TableBuilder::renameTableSql()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
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
        $tableSchema = array_filter([$this->columnsSql(), $this->indexesSql()]);
31
        $sql = '';
32
33
        if ($tableSchema) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $tableSchema of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
34
            $sql = 'CREATE TABLE `' . $this->name . '` (';
35
            $sql .= implode(', ', $tableSchema);
36
            $sql .= ');';
37
        }
38
39
        return $sql;
40
    }
41
42
    /**
43
     * Generates alter table statement
44
     * @return string
45
     */
46
    protected function alterTableSql(): string
47
    {
48
        $tableSchema = array_filter([$this->columnsSql(), $this->indexesSql(), $this->dropIndexesSql()]);
49
        $sql = '';
50
51
        if ($tableSchema) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $tableSchema of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
52
            $sql = 'ALTER TABLE `' . $this->name . '` ';
53
            $sql .= implode(', ', $tableSchema);
54
            $sql .= ';';
55
        }
56
57
        return $sql;
58
    }
59
60
    /**
61
     * Prepares rename table statement
62
     * @return string
63
     */
64
    protected function renameTableSql(): string
65
    {
66
        return 'RENAME TABLE `' . $this->name . '` TO `' . $this->newName . '`;';
67
    }
68
69
    /**
70
     * Prepares drop table statement
71
     * @return string
72
     */
73
    protected function dropTableSql(): string
74
    {
75
        return 'DROP TABLE `' . $this->name . '`';
76
    }
77
78
    /**
79
     * Prepares columns statements for table
80
     * @return string
81
     */
82
    protected function columnsSql(): string
83
    {
84
        $sql = '';
85
86
        if ($this->columns) {
87
            $columns = [];
88
89
            foreach ($this->columns as $entry) {
90
                $columnString = '';
91
92
                if ($entry['action'] != Column::ADD_INDEX && $entry['action'] != Column::DROP_INDEX) {
93
                    $columnString .= ($entry['action'] ? $entry['action'] . ' COLUMN ' : '');
94
                    $columnString .= $this->composeColumn($entry['column'], $entry['action']);
95
                }
96
97
                if ($entry['column']->get('indexKey')) {
98
                    $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...
99
                        'columnName' => $entry['column']->get('name'),
100
                        'indexName' => $entry['column']->get('indexName'),
101
                    ];
102
                }
103
104
                if ($entry['column']->get('indexDrop')) {
105
                    $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...
106
                }
107
108
                if ($columnString) {
109
                    array_push($columns, $columnString);
110
                }
111
            }
112
113
            $sql = implode(', ', $columns);
114
        }
115
116
        return $sql;
117
    }
118
119
    /**
120
     * Composes the column 
121
     * @param Column $column
122
     * @param string $action
123
     * @return string
124
     */
125
    protected function composeColumn(Column $column, string $action = null): string
126
    {
127
        return
128
                $this->columnAttrSql($column->get(Column::NAME), '`', '`') .
129
                $this->columnAttrSql($column->get(Column::NEW_NAME), ' TO `', '`') .
130
                $this->columnAttrSql($column->get(Column::TYPE), ' ') .
131
                $this->columnAttrSql($column->get(Column::CONSTRAINT), '(', ')') .
132
                $this->columnAttrSql($column->get(Column::ATTRIBUTE), ' ') .
133
                $this->columnAttrSql($column->get(Column::NULLABLE, $action), ' ',) .
134
                $this->columnAttrSql($column->get(Column::DEFAULT), ' DEFAULT ' . ($column->defaultQuoted() ? '\'' : ''), ($column->defaultQuoted() ? '\'' : '')) .
135
                $this->columnAttrSql($column->get(Column::COMMENT), ' COMMENT \'', '\'') .
136
                $this->columnAttrSql($column->get(Column::AFTER), ' AFTER `', '`') .
137
                $this->columnAttrSql($column->get(Column::AUTO_INCREMENT), ' ');
138
    }
139
140
    /**
141
     * Prepares column attributes
142
     * @param mixed $definition
143
     * @param string $before
144
     * @param string $after
145
     * @return string
146
     */
147
    protected function columnAttrSql($definition, string $before = '', string $after = ''): string
148
    {
149
        $sql = '';
150
151
        if (!is_null($definition)) {
152
153
            $sql .= $before . (is_array($definition) ? ("'" . implode("', '", $definition) . "'") : $definition) . $after;
154
        }
155
156
        return $sql;
157
    }
158
159
    /**
160
     * Prepares statement for primary key
161
     * @return string
162
     */
163
    protected function primaryKeysSql(): string
164
    {
165
        $sql = '';
166
167
        if (isset($this->indexKeys['primary'])) {
168
            $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...
169
170
            $sql .= 'PRIMARY KEY (';
171
172
            foreach ($this->indexKeys['primary'] as $key => $primaryKey) {
173
                $sql .= '`' . $primaryKey['columnName'] . '`';
174
                $sql .= (array_key_last($this->indexKeys['primary']) != $key ? ', ' : '');
175
            }
176
177
            $sql .= ')';
178
        }
179
180
        return $sql;
181
    }
182
183
    /**
184
     * Prepares statement for index keys
185
     * @param string $type
186
     * @return string
187
     */
188
    protected function indexKeysSql(string $type): string
189
    {
190
        $sql = '';
191
192
        if (isset($this->indexKeys[$type])) {
193
            $indexes = [];
194
195
            foreach ($this->indexKeys[$type] as $indexKey) {
196
                $indexString = '';
197
198
                $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...
199
                $indexString .= strtoupper($type);
200
                $indexString .= ($indexKey['indexName'] ? ' `' . $indexKey['indexName'] . '`' : '');
201
                $indexString .= ' (`' . $indexKey['columnName'] . '`)';
202
203
                array_push($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()
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
}
251