DDL   A
last analyzed

Complexity

Total Complexity 23

Size/Duplication

Total Lines 229
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 229
rs 10
c 0
b 0
f 0
wmc 23
lcom 1
cbo 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
B create() 0 29 3
B _createColumns() 0 26 4
B _createColumnPart() 0 25 5
B _createForeigns() 0 28 3
A drop() 0 11 2
B index() 0 22 4
A optimize() 0 12 2
1
<?php
2
3
/**
4
 * Contains query string build tools for data definition
5
 *
6
 * PHP Version 5
7
 *
8
 * @category  Core
9
 * @package   SQL
10
 * @author    Hans-Joachim Piepereit <[email protected]>
11
 * @copyright 2013 cSphere Team
12
 * @license   http://opensource.org/licenses/bsd-license Simplified BSD License
13
 * @link      http://www.csphere.eu
14
 **/
15
16
namespace csphere\core\sql;
17
18
/**
19
 * Contains query string build tools for data definition
20
 *
21
 * @category  Core
22
 * @package   SQL
23
 * @author    Hans-Joachim Piepereit <[email protected]>
24
 * @copyright 2013 cSphere Team
25
 * @license   http://opensource.org/licenses/bsd-license Simplified BSD License
26
 * @link      http://www.csphere.eu
27
 **/
28
29
abstract class DDL
30
{
31
    /**
32
     * Creates a new database table
33
     *
34
     * @param string $table    Name of the database table
35
     * @param array  $columns  Names of the database columns
36
     * @param array  $primary  Columns to use for the primary key
37
     * @param array  $foreigns Foreign keys to apply to the table
38
     *
39
     * @throws \Exception
40
     *
41
     * @return array
42
     **/
0 ignored issues
show
Coding Style introduced by
There must be no blank lines after the function comment
Loading history...
43
44
    public static function create(
45
        $table, array $columns, array $primary, array $foreigns = []
46
    ) {
47
        // Build a matching create query
48
        $query = 'CREATE TABLE {pre}' . $table . ' (';
49
50
        // Add columns
51
        $query .= self::_createColumns($columns);
52
53
        // Add primary key
54
        $query .= 'PRIMARY KEY (';
55
56
        foreach ($primary AS $column) {
57
58
            $query .= $column['name'] . ', ';
59
        }
60
61
        $query = substr($query, 0, -2) . ')';
62
63
        // Add foreign keys
64
        if ($foreigns != []) {
65
66
            $query .= ', ' . self::_createForeigns($foreigns);
67
        }
68
69
        $query .= '){engine}';
70
71
        return ['statement' => $query, 'input' => []];
72
    }
73
74
    /**
75
     * Creates the column parts for table creation
76
     *
77
     * @param array $columns Array with columns
78
     *
79
     * @throws \Exception
80
     *
81
     * @return string
82
     **/
0 ignored issues
show
Coding Style introduced by
There must be no blank lines after the function comment
Loading history...
83
84
    private static function _createColumns(array $columns)
85
    {
86
        $serial = 0;
87
        $query  = '';
88
89
        foreach ($columns AS $column) {
90
91
            // Count serials since one is required
92
            if ($column['datatype'] == 'serial') {
93
94
                $serial++;
95
            }
96
97
            $query .= self::_createColumnPart($column) . ', ';
98
        }
99
100
        // Check if there is exactly one serial
101
        if ($serial != 1) {
102
103
            $msg = 'Need exactly one serial column, but found: ' . $serial;
104
105
            throw new \Exception($msg);
106
        }
107
108
        return $query;
109
    }
110
111
    /**
112
     * Creates the part of a single column
113
     *
114
     * @param array $column Array with column details
115
     *
116
     * @return string
117
     **/
0 ignored issues
show
Coding Style introduced by
There must be no blank lines after the function comment
Loading history...
118
119
    private static function _createColumnPart(array $column)
120
    {
121
        // Some column types may have a limit in length
122
        $max  = '';
123
124
        if (!empty($column['max']) && $column['datatype'] == 'varchar') {
125
126
            $max = '(' . (int)$column['max'] . ')';
127
        }
128
129
        // Some columns might provide a default value
130
        $default = ' NOT NULL';
131
132
        if (isset($column['default']) && $column['default'] != '') {
133
134
            $default .= ' DEFAULT \'' . $column['default'] . '\'';
135
        }
136
137
        // Generate query part
138
        $query = $column['name']
139
               . ' {' . $column['datatype'] . '}' . $max
140
               . $default;
141
142
        return $query;
143
    }
144
145
    /**
146
     * Creates the foreign key parts for table creation
147
     *
148
     * @param array $foreigns Array with foreign keys
149
     *
150
     * @return string
151
     **/
0 ignored issues
show
Coding Style introduced by
There must be no blank lines after the function comment
Loading history...
152
153
    private static function _createForeigns(array $foreigns)
154
    {
155
156
        $query = '';
157
158
        foreach ($foreigns AS $foreign) {
159
160
            $ref = $foreign['table'];
161
            $names = '';
162
            $targets = '';
163
164
            $query .= 'FOREIGN KEY (';
165
166
            // Add column name and its target per element
167
            foreach ($foreign['column'] AS $column) {
168
169
                $names .= $column['name'] . ', ';
170
                $targets .= $column['target'] . ', ';
171
            }
172
173
            $query .= substr($names, 0, -2) . ') REFERENCES {pre}' . $ref;
174
            $query .= ' (' . substr($targets, 0, -2) . '), ';
175
        }
176
177
        $query = substr($query, 0, -2);
178
179
        return $query;
180
    }
181
182
    /**
183
     * Drops a database table
184
     *
185
     * @param string  $table     Name of the database table
186
     * @param boolean $if_exists Defaults to true while ignoring not found errors
187
     *
188
     * @return array
189
     **/
0 ignored issues
show
Coding Style introduced by
There must be no blank lines after the function comment
Loading history...
190
191
    public static function drop($table, $if_exists = true)
192
    {
193
        // Build a matching drop query
194
        $query = 'DROP TABLE ';
195
196
        $query .= empty($if_exists) ? '' : 'IF EXISTS ';
197
198
        $query .= '{pre}' . $table;
199
200
        return ['statement' => $query, 'input' => []];
201
    }
202
203
    /**
204
     * Creates a new index
205
     *
206
     * @param string  $name    Name for the index to create
207
     * @param string  $table   Name of the database table
208
     * @param array   $columns Columns to use for the index
209
     * @param boolean $unique  Enforces combined column data to be unique
210
     *
211
     * @return array
212
     **/
0 ignored issues
show
Coding Style introduced by
There must be no blank lines after the function comment
Loading history...
213
214
    public static function index($name, $table, array $columns, $unique = false)
215
    {
216
        // Build a matching index query
217
        $query = empty($unique) ? 'CREATE INDEX ' : 'CREATE UNIQUE INDEX ';
218
219
        $query .= $name . ' ON {pre}' . $table . ' (';
220
221
        foreach ($columns AS $key) {
222
223
            // Column array can be build up with a name tag
224
            if (isset($key['name'])) {
225
226
                $key = $key['name'];
227
            }
228
229
            $query .= $key . ', ';
230
        }
231
232
        $query = substr($query, 0, -2) . ')';
233
234
        return ['statement' => $query, 'input' => []];
235
    }
236
237
    /**
238
     * Optimizes database tables
239
     *
240
     * @param array $tables Names of the database tables
241
     *
242
     * @return array
243
     **/
0 ignored issues
show
Coding Style introduced by
There must be no blank lines after the function comment
Loading history...
244
245
    public static function optimize(array $tables)
246
    {
247
        // Build a matching optimize query
248
        $query = '';
249
250
        foreach ($tables AS $table) {
251
252
            $query .= '{optimize} {pre}' . $table . ';' . "\n";
253
        }
254
255
        return ['statement' => $query, 'input' => []];
256
    }
257
}
258