Completed
Pull Request — master (#144)
by Michael
03:08
created

SqlFile::getDatabaseFields()   F

Complexity

Conditions 47
Paths 6363

Size

Total Lines 166
Code Lines 144

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 47
eloc 144
nc 6363
nop 6
dl 0
loc 166
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace XoopsModules\Tdmcreate\Files\Sql;
4
5
use XoopsModules\Tdmcreate;
6
use XoopsModules\Tdmcreate\Files;
7
8
/*
9
 You may not change or alter any portion of this comment or credits
10
 of supporting developers from this source code or any supporting source code
11
 which is considered copyrighted (c) material of the original comment or credit authors.
12
13
 This program is distributed in the hope that it will be useful,
14
 but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16
 */
17
/**
18
 * tdmcreate module.
19
 *
20
 * @copyright       XOOPS Project (https://xoops.org)
21
 * @license         GNU GPL 2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)
22
 *
23
 * @since           2.5.0
24
 *
25
 * @author          Txmod Xoops http://www.txmodxoops.org
26
 *
27
 */
28
29
/**
30
 * Class SqlFile.
31
 */
32
class SqlFile extends Files\CreateFile
33
{
34
    /**
35
     * @public function constructor
36
     *
37
     * @param null
38
     */
39
    public function __construct()
40
    {
41
        parent::__construct();
42
    }
43
44
    /**
45
     * @static function getInstance
46
     *
47
     * @param null
48
     *
49
     * @return SqlFile
50
     */
51
    public static function getInstance()
52
    {
53
        static $instance = false;
54
        if (!$instance) {
55
            $instance = new self();
56
        }
57
58
        return $instance;
59
    }
60
61
    /**
62
     * @public function write
63
     *
64
     * @param $module
65
     * @param $filename
66
     */
67
    public function write($module, $filename)
68
    {
69
        $this->setModule($module);
70
        $this->setFileName($filename);
71
    }
72
73
    /**
74
     * @private function getHeaderSqlComments
75
     *
76
     * @param $moduleName
77
     *
78
     * @return string
79
     */
80
    private function getHeaderSqlComments($moduleName)
81
    {
82
        $date          = date('D M d, Y');
83
        $time          = date('H:i:s');
84
        $serverName    = \Xmf\Request::getString('SERVER_NAME', '', 'SERVER');
85
        $serverVersion = $GLOBALS['xoopsDB']->getServerVersion();
86
        $phpVersion    = PHP_VERSION;
87
        // Header Sql Comments
88
        $ret             = null;
89
        $arrayServerInfo = [
90
            "# SQL Dump for {$moduleName} module",
91
            '# PhpMyAdmin Version: 4.0.4',
92
            '# http://www.phpmyadmin.net',
93
            '#',
94
            "# Host: {$serverName}",
95
            "# Generated on: {$date} to {$time}",
96
            "# Server version: {$serverVersion}",
97
            "# PHP Version: {$phpVersion}\n",
98
        ];
99
        foreach ($arrayServerInfo as $serverInfo) {
100
            $ret .= $this->getSimpleString($serverInfo);
101
        }
102
103
        return $ret;
104
    }
105
106
    /**
107
     * @private function getHeadDatabaseTable
108
     * @param     $moduleDirname
109
     * @param     $tableName
110
     * @param int $fieldsNumb
111
     *
112
     *  Unused IF NOT EXISTS
113
     *
114
     * @return string
115
     */
116
    private function getHeadDatabaseTable($moduleDirname, $tableName, $fieldsNumb)
117
    {
118
        $ret          = null;
119
        $arrayDbTable = [
120
            '#',
121
            "# Structure table for `{$moduleDirname}_{$tableName}` {$fieldsNumb}",
122
            '#',
123
            "\nCREATE TABLE `{$moduleDirname}_{$tableName}` (",
124
        ];
125
        foreach ($arrayDbTable as $dbTable) {
126
            $ret .= $this->getSimpleString($dbTable);
127
        }
128
129
        return $ret;
130
    }
131
132
    /**
133
     * @private function getDatabaseTables
134
     *
135
     * @param $module
136
     *
137
     * @return null|string
138
     */
139
    private function getDatabaseTables($module)
140
    {
141
        $ret           = null;
142
        $moduleDirname = mb_strtolower($module->getVar('mod_dirname'));
143
        $tables        = $this->getTableTables($module->getVar('mod_id'), 'table_order ASC, table_id');
144
        foreach (array_keys($tables) as $t) {
145
            $tableId            = $tables[$t]->getVar('table_id');
146
            $tableMid           = $tables[$t]->getVar('table_mid');
147
            $tableName          = $tables[$t]->getVar('table_name');
148
            $tableAutoincrement = $tables[$t]->getVar('table_autoincrement');
149
            $fieldsNumb         = $tables[$t]->getVar('table_nbfields');
150
            $ret                .= $this->getDatabaseFields($moduleDirname, $tableMid, $tableId, $tableName, $tableAutoincrement, $fieldsNumb);
151
        }
152
153
        return $ret;
154
    }
155
156
    /**
157
     * @private function getDatabaseFields
158
     *
159
     * @param $moduleDirname
160
     * @param $tableMid
161
     * @param $tableId
162
     * @param $tableName
163
     * @param $tableAutoincrement
164
     * @param $fieldsNumb
165
     * @return null|string
166
     */
167
    private function getDatabaseFields($moduleDirname, $tableMid, $tableId, $tableName, $tableAutoincrement, $fieldsNumb)
168
    {
169
        $helper = Tdmcreate\Helper::getInstance();
170
        $ret    = null;
171
        $j      = 0;
172
        $comma  = [];
173
        $row    = [];
174
        $type   = '';
175
        $fields = $this->getTableFields($tableMid, $tableId, 'field_id ASC, field_name');
176
        foreach (array_keys($fields) as $f) {
177
            // Creation of database table
178
            $ret            = $this->getHeadDatabaseTable($moduleDirname, $tableName, $fieldsNumb);
179
            $fieldName      = $fields[$f]->getVar('field_name');
180
            $fieldType      = $fields[$f]->getVar('field_type');
181
            $fieldValue     = $fields[$f]->getVar('field_value');
182
            $fieldAttribute = $fields[$f]->getVar('field_attribute');
183
            $fieldNull      = $fields[$f]->getVar('field_null');
184
            $fieldDefault   = $fields[$f]->getVar('field_default');
185
            $fieldKey       = $fields[$f]->getVar('field_key');
186
            if ($fieldType > 1) {
187
                $fType         = $helper->getHandler('Fieldtype')->get($fieldType);
188
                $fieldTypeName = $fType->getVar('fieldtype_name');
189
            } else {
190
                $fieldType = null;
191
            }
192
            if ($fieldAttribute > 1) {
193
                $fAttribute     = $helper->getHandler('Fieldattributes')->get($fieldAttribute);
194
                $fieldAttribute = $fAttribute->getVar('fieldattribute_name');
195
            } else {
196
                $fieldAttribute = null;
197
            }
198
            if ($fieldNull > 1) {
199
                $fNull     = $helper->getHandler('Fieldnull')->get($fieldNull);
200
                $fieldNull = $fNull->getVar('fieldnull_name');
201
            } else {
202
                $fieldNull = null;
203
            }
204
            if (!empty($fieldName)) {
205
                switch ($fieldType) {
206
                    case 2:
207
                    case 3:
208
                    case 4:
209
                    case 5:
210
                        $type = $fieldTypeName . '(' . $fieldValue . ')';
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $fieldTypeName does not seem to be defined for all execution paths leading up to this point.
Loading history...
211
                        if (empty($fieldDefault)) {
212
                            $default = "DEFAULT '0'";
213
                        } else {
214
                            $default = "DEFAULT '{$fieldDefault}'";
215
                        }
216
                        break;
217
                    case 6:
218
                    case 7:
219
                    case 8:
220
                        $type = $fieldTypeName . '(' . $fieldValue . ')';
221
                        if (empty($fieldDefault)) {
222
                            $default = "DEFAULT '0.00'"; // From MySQL 5.7 Manual
223
                        } else {
224
                            $default = "DEFAULT '{$fieldDefault}'";
225
                        }
226
                        break;
227
                    case 9:
228
                    case 10:
229
                        $fValues = str_replace(',', "', '", str_replace(' ', '', $fieldValue));
230
                        $type    = $fieldTypeName . '(\'' . $fValues . '\')'; // Used with comma separator
231
                        $default = "DEFAULT '{$fieldDefault}'";
232
                        break;
233
                    case 11:
234
                        $type = $fieldTypeName . '(' . $fieldValue . ')';
235
                        if (empty($fieldDefault)) {
236
                            $default = "DEFAULT '[email protected]'";
237
                        } else {
238
                            $default = "DEFAULT '{$fieldDefault}'";
239
                        }
240
                        break;
241
                    case 12:
242
                        $type = $fieldTypeName . '(' . $fieldValue . ')';
243
                        if (empty($fieldDefault)) {
244
                            $default = "DEFAULT 'http:\\'";
245
                        } else {
246
                            $default = "DEFAULT '{$fieldDefault}'";
247
                        }
248
                        break;
249
                    case 13:
250
                    case 14:
251
                        $type    = $fieldTypeName . '(' . $fieldValue . ')';
252
                        $default = "DEFAULT '{$fieldDefault}'";
253
                        break;
254
                    case 15:
255
                    case 16:
256
                    case 17:
257
                    case 18:
258
                        $type    = $fieldTypeName;
259
                        $default = null;
260
                        break;
261
                    case 19:
262
                    case 20:
263
                    case 21:
264
                    case 22:
265
                        $type    = $fieldTypeName . '(' . $fieldValue . ')';
266
                        $default = "DEFAULT '{$fieldDefault}'";
267
                        break;
268
                    case 23:
269
                        $type = $fieldTypeName;
270
                        if (empty($fieldDefault)) {
271
                            $default = "DEFAULT '1970'"; // From MySQL 5.7 Manual
272
                        } else {
273
                            $default = "DEFAULT '{$fieldDefault}'";
274
                        }
275
                        break;
276
                    default:
277
                        $type    = $fieldTypeName . '(' . $fieldValue . ')';
278
                        $default = "DEFAULT '{$fieldDefault}'";
279
                        break;
280
                }
281
                if ((0 == $f) && (1 == $tableAutoincrement)) {
282
                    $row[]     = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, null, 'AUTO_INCREMENT');
283
                    $comma[$j] = $this->getKey(2, $fieldName);
284
                    ++$j;
285
                } elseif ((0 == $f) && (0 == $tableAutoincrement)) {
286
                    $row[]     = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
287
                    $comma[$j] = $this->getKey(2, $fieldName);
288
                    ++$j;
289
                } else {
290
                    if (3 == $fieldKey || 4 == $fieldKey || 5 == $fieldKey || 6 == $fieldKey) {
291
                        switch ($fieldKey) {
292
                            case 3:
293
                                $row[]     = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
294
                                $comma[$j] = $this->getKey(3, $fieldName);
295
                                ++$j;
296
                                break;
297
                            case 4:
298
                                $row[]     = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
299
                                $comma[$j] = $this->getKey(4, $fieldName);
300
                                ++$j;
301
                                break;
302
                            case 5:
303
                                $row[]     = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
304
                                $comma[$j] = $this->getKey(5, $fieldName);
305
                                ++$j;
306
                                break;
307
                            case 6:
308
                                $row[]     = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
309
                                $comma[$j] = $this->getKey(6, $fieldName);
310
                                ++$j;
311
                                break;
312
                        }
313
                    } else {
314
                        $row[] = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
315
                    }
316
                }
317
            }
318
        }
319
        // ================= COMMA ================= //
320
        for ($i = 0; $i < $j; ++$i) {
321
            if ($i != $j - 1) {
322
                $row[] = $comma[$i] . ',';
323
            } else {
324
                $row[] = $comma[$i];
325
            }
326
        }
327
        // ================= COMMA CICLE ================= //
328
        $ret .= implode("\n", $row);
329
        unset($j);
330
        $ret .= $this->getFootDatabaseTable();
331
332
        return $ret;
333
    }
334
335
    /**
336
     * @private function getFootDatabaseTable
337
     *
338
     * @param null
339
     *
340
     * @return string
341
     */
342
    private function getFootDatabaseTable()
343
    {
344
        return "\n) ENGINE=InnoDB;\n\n";
345
    }
346
347
    /**
348
     * @private function getFieldRow
349
     *
350
     * @param $fieldName
351
     * @param $fieldTypeValue
352
     * @param $fieldAttribute
353
     * @param $fieldNull
354
     * @param $fieldDefault
355
     * @param $autoincrement
356
     *
357
     * @return string
358
     */
359
    private function getFieldRow($fieldName, $fieldTypeValue, $fieldAttribute = null, $fieldNull = null, $fieldDefault = null, $autoincrement = null)
360
    {
361
        $retAutoincrement  = "  `{$fieldName}` {$fieldTypeValue} {$fieldAttribute} {$fieldNull} {$autoincrement},";
362
        $retFieldAttribute = "  `{$fieldName}` {$fieldTypeValue} {$fieldAttribute} {$fieldNull} {$fieldDefault},";
363
        $fieldDefault      = "  `{$fieldName}` {$fieldTypeValue} {$fieldNull} {$fieldDefault},";
364
        $retShort          = "  `{$fieldName}` {$fieldTypeValue},";
365
366
        $ret = $retShort;
367
        if (null != $autoincrement) {
368
            $ret = $retAutoincrement;
369
        } elseif (null != $fieldAttribute) {
370
            $ret = $retFieldAttribute;
371
        } elseif (null === $fieldAttribute) {
372
            $ret = $fieldDefault;
373
        }
374
375
        return $ret;
376
    }
377
378
    /**
379
     * @private function getKey
380
     *
381
     * @param $key
382
     * @param $fieldName
383
     * @return string
384
     */
385
    private function getKey($key, $fieldName)
386
    {
387
        $ret = null;
388
        switch ($key) {
389
            case 2: // PRIMARY KEY
390
                $ret = "  PRIMARY KEY (`{$fieldName}`)";
391
                break;
392
            case 3: // UNIQUE KEY
393
                $ret = "  UNIQUE KEY `{$fieldName}` (`{$fieldName}`)";
394
                break;
395
            case 4: // KEY
396
                $ret = "  KEY `{$fieldName}` (`{$fieldName}`)";
397
                break;
398
            case 5: // INDEX
399
                $ret = "  INDEX (`{$fieldName}`)";
400
                break;
401
            case 6: // FULLTEXT KEY
402
                $ret = "  FULLTEXT KEY `{$fieldName}` (`{$fieldName}`)";
403
                break;
404
        }
405
406
        return $ret;
407
    }
408
409
    /**
410
     * @private function getComma
411
     *
412
     * @param $row
413
     * @param $comma
414
     *
415
     * @return string
416
     */
417
    private function getComma($row, $comma = null)
418
    {
419
        return " {$row}{$comma}";
420
    }
421
422
    /**
423
     * @private function getCommaCicle
424
     *
425
     * @param $comma
426
     * @param $index
427
     *
428
     * @return string
429
     */
430
    private function getCommaCicle($comma, $index)
0 ignored issues
show
Unused Code introduced by
The method getCommaCicle() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
431
    {
432
        $ret = null;
433
        // Comma issue
434
        for ($i = 1; $i <= $index; ++$i) {
435
            if ($i != $index - 1) {
436
                $ret = $this->getComma(isset($comma[$i]), ',') . "\n";
437
            } else {
438
                $ret = $this->getComma(isset($comma[$i])) . "\n";
439
            }
440
        }
441
442
        return $ret;
443
    }
444
445
    /**
446
     * @public function render
447
     *
448
     * @param null
449
     *
450
     * @return bool|string
451
     */
452
    public function render()
453
    {
454
        $module        = $this->getModule();
455
        $filename      = $this->getFileName();
456
        $moduleName    = mb_strtolower($module->getVar('mod_name'));
457
        $moduleDirname = mb_strtolower($module->getVar('mod_dirname'));
458
        $content       = $this->getHeaderSqlComments($moduleName);
459
        $content       .= $this->getDatabaseTables($module);
460
461
        $this->create($moduleDirname, 'sql', $filename, $content, _AM_TDMCREATE_FILE_CREATED, _AM_TDMCREATE_FILE_NOTCREATED);
462
463
        return $this->renderFile();
464
    }
465
}
466