Completed
Pull Request — master (#144)
by Michael
03:13
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
 * @version         $Id: SqlFile.php 12258 2014-01-02 09:33:29Z timgno $
28
 */
29
30
/**
31
 * Class SqlFile.
32
 */
33
class SqlFile extends Files\CreateFile
34
{
35
    /**
36
     * @public function constructor
37
     *
38
     * @param null
39
     */
40
    public function __construct()
41
    {
42
        parent::__construct();
43
    }
44
45
    /**
46
     * @static function getInstance
47
     *
48
     * @param null
49
     *
50
     * @return SqlFile
51
     */
52
    public static function getInstance()
53
    {
54
        static $instance = false;
55
        if (!$instance) {
56
            $instance = new self();
57
        }
58
59
        return $instance;
60
    }
61
62
    /**
63
     * @public function write
64
     *
65
     * @param $module
66
     * @param $filename
67
     */
68
    public function write($module, $filename)
69
    {
70
        $this->setModule($module);
71
        $this->setFileName($filename);
72
    }
73
74
    /**
75
     * @private function getHeaderSqlComments
76
     *
77
     * @param $moduleName
78
     *
79
     * @return string
80
     */
81
    private function getHeaderSqlComments($moduleName)
82
    {
83
        $date          = date('D M d, Y');
84
        $time          = date('H:i:s');
85
        $serverName    = $_SERVER['SERVER_NAME'];
86
        $serverVersion = $GLOBALS['xoopsDB']->getServerVersion();
87
        $phpVersion    = PHP_VERSION;
88
        // Header Sql Comments
89
        $ret             = null;
90
        $arrayServerInfo = [
91
            "# SQL Dump for {$moduleName} module",
92
            '# PhpMyAdmin Version: 4.0.4',
93
            '# http://www.phpmyadmin.net',
94
            '#',
95
            "# Host: {$serverName}",
96
            "# Generated on: {$date} to {$time}",
97
            "# Server version: {$serverVersion}",
98
            "# PHP Version: {$phpVersion}\n",
99
        ];
100
        foreach ($arrayServerInfo as $serverInfo) {
101
            $ret .= $this->getSimpleString($serverInfo);
102
        }
103
104
        return $ret;
105
    }
106
107
    /**
108
     * @private function getHeadDatabaseTable
109
     * @param     $moduleDirname
110
     * @param     $tableName
111
     * @param int $fieldsNumb
112
     *
113
     *  Unused IF NOT EXISTS
114
     *
115
     * @return string
116
     */
117
    private function getHeadDatabaseTable($moduleDirname, $tableName, $fieldsNumb)
118
    {
119
        $ret          = null;
120
        $arrayDbTable = [
121
            '#',
122
            "# Structure table for `{$moduleDirname}_{$tableName}` {$fieldsNumb}",
123
            '#',
124
            "\nCREATE TABLE `{$moduleDirname}_{$tableName}` (",
125
        ];
126
        foreach ($arrayDbTable as $dbTable) {
127
            $ret .= $this->getSimpleString($dbTable);
128
        }
129
130
        return $ret;
131
    }
132
133
    /**
134
     * @private function getDatabaseTables
135
     *
136
     * @param $module
137
     *
138
     * @return null|string
139
     */
140
    private function getDatabaseTables($module)
141
    {
142
        $ret           = null;
143
        $moduleDirname = mb_strtolower($module->getVar('mod_dirname'));
144
        $tables        = $this->getTableTables($module->getVar('mod_id'), 'table_order ASC, table_id');
145
        foreach (array_keys($tables) as $t) {
146
            $tableId            = $tables[$t]->getVar('table_id');
147
            $tableMid           = $tables[$t]->getVar('table_mid');
148
            $tableName          = $tables[$t]->getVar('table_name');
149
            $tableAutoincrement = $tables[$t]->getVar('table_autoincrement');
150
            $fieldsNumb         = $tables[$t]->getVar('table_nbfields');
151
            $ret                .= $this->getDatabaseFields($moduleDirname, $tableMid, $tableId, $tableName, $tableAutoincrement, $fieldsNumb);
152
        }
153
154
        return $ret;
155
    }
156
157
    /**
158
     * @private function getDatabaseFields
159
     *
160
     * @param $moduleDirname
161
     * @param $tableMid
162
     * @param $tableId
163
     * @param $tableName
164
     * @param $tableAutoincrement
165
     * @param $fieldsNumb
166
     * @return null|string
167
     */
168
    private function getDatabaseFields($moduleDirname, $tableMid, $tableId, $tableName, $tableAutoincrement, $fieldsNumb)
169
    {
170
        $helper = Tdmcreate\Helper::getInstance();
171
        $ret    = null;
172
        $j      = 0;
173
        $comma  = [];
174
        $row    = [];
175
        $type   = '';
176
        $fields = $this->getTableFields($tableMid, $tableId, 'field_id ASC, field_name');
177
        foreach (array_keys($fields) as $f) {
178
            // Creation of database table
179
            $ret            = $this->getHeadDatabaseTable($moduleDirname, $tableName, $fieldsNumb);
180
            $fieldName      = $fields[$f]->getVar('field_name');
181
            $fieldType      = $fields[$f]->getVar('field_type');
182
            $fieldValue     = $fields[$f]->getVar('field_value');
183
            $fieldAttribute = $fields[$f]->getVar('field_attribute');
184
            $fieldNull      = $fields[$f]->getVar('field_null');
185
            $fieldDefault   = $fields[$f]->getVar('field_default');
186
            $fieldKey       = $fields[$f]->getVar('field_key');
187
            if ($fieldType > 1) {
188
                $fType         = $helper->getHandler('Fieldtype')->get($fieldType);
189
                $fieldTypeName = $fType->getVar('fieldtype_name');
190
            } else {
191
                $fieldType = null;
192
            }
193
            if ($fieldAttribute > 1) {
194
                $fAttribute     = $helper->getHandler('Fieldattributes')->get($fieldAttribute);
195
                $fieldAttribute = $fAttribute->getVar('fieldattribute_name');
196
            } else {
197
                $fieldAttribute = null;
198
            }
199
            if ($fieldNull > 1) {
200
                $fNull     = $helper->getHandler('Fieldnull')->get($fieldNull);
201
                $fieldNull = $fNull->getVar('fieldnull_name');
202
            } else {
203
                $fieldNull = null;
204
            }
205
            if (!empty($fieldName)) {
206
                switch ($fieldType) {
207
                    case 2:
208
                    case 3:
209
                    case 4:
210
                    case 5:
211
                        $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...
212
                        if (empty($fieldDefault)) {
213
                            $default = "DEFAULT '0'";
214
                        } else {
215
                            $default = "DEFAULT '{$fieldDefault}'";
216
                        }
217
                        break;
218
                    case 6:
219
                    case 7:
220
                    case 8:
221
                        $type = $fieldTypeName . '(' . $fieldValue . ')';
222
                        if (empty($fieldDefault)) {
223
                            $default = "DEFAULT '0.00'"; // From MySQL 5.7 Manual
224
                        } else {
225
                            $default = "DEFAULT '{$fieldDefault}'";
226
                        }
227
                        break;
228
                    case 9:
229
                    case 10:
230
                        $fValues = str_replace(',', "', '", str_replace(' ', '', $fieldValue));
231
                        $type    = $fieldTypeName . '(\'' . $fValues . '\')'; // Used with comma separator
232
                        $default = "DEFAULT '{$fieldDefault}'";
233
                        break;
234
                    case 11:
235
                        $type = $fieldTypeName . '(' . $fieldValue . ')';
236
                        if (empty($fieldDefault)) {
237
                            $default = "DEFAULT '[email protected]'";
238
                        } else {
239
                            $default = "DEFAULT '{$fieldDefault}'";
240
                        }
241
                        break;
242
                    case 12:
243
                        $type = $fieldTypeName . '(' . $fieldValue . ')';
244
                        if (empty($fieldDefault)) {
245
                            $default = "DEFAULT 'http:\\'";
246
                        } else {
247
                            $default = "DEFAULT '{$fieldDefault}'";
248
                        }
249
                        break;
250
                    case 13:
251
                    case 14:
252
                        $type    = $fieldTypeName . '(' . $fieldValue . ')';
253
                        $default = "DEFAULT '{$fieldDefault}'";
254
                        break;
255
                    case 15:
256
                    case 16:
257
                    case 17:
258
                    case 18:
259
                        $type    = $fieldTypeName;
260
                        $default = null;
261
                        break;
262
                    case 19:
263
                    case 20:
264
                    case 21:
265
                    case 22:
266
                        $type    = $fieldTypeName . '(' . $fieldValue . ')';
267
                        $default = "DEFAULT '{$fieldDefault}'";
268
                        break;
269
                    case 23:
270
                        $type = $fieldTypeName;
271
                        if (empty($fieldDefault)) {
272
                            $default = "DEFAULT '1970'"; // From MySQL 5.7 Manual
273
                        } else {
274
                            $default = "DEFAULT '{$fieldDefault}'";
275
                        }
276
                        break;
277
                    default:
278
                        $type    = $fieldTypeName . '(' . $fieldValue . ')';
279
                        $default = "DEFAULT '{$fieldDefault}'";
280
                        break;
281
                }
282
                if ((0 == $f) && (1 == $tableAutoincrement)) {
283
                    $row[]     = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, null, 'AUTO_INCREMENT');
284
                    $comma[$j] = $this->getKey(2, $fieldName);
285
                    ++$j;
286
                } elseif ((0 == $f) && (0 == $tableAutoincrement)) {
287
                    $row[]     = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
288
                    $comma[$j] = $this->getKey(2, $fieldName);
289
                    ++$j;
290
                } else {
291
                    if (3 == $fieldKey || 4 == $fieldKey || 5 == $fieldKey || 6 == $fieldKey) {
292
                        switch ($fieldKey) {
293
                            case 3:
294
                                $row[]     = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
295
                                $comma[$j] = $this->getKey(3, $fieldName);
296
                                ++$j;
297
                                break;
298
                            case 4:
299
                                $row[]     = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
300
                                $comma[$j] = $this->getKey(4, $fieldName);
301
                                ++$j;
302
                                break;
303
                            case 5:
304
                                $row[]     = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
305
                                $comma[$j] = $this->getKey(5, $fieldName);
306
                                ++$j;
307
                                break;
308
                            case 6:
309
                                $row[]     = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
310
                                $comma[$j] = $this->getKey(6, $fieldName);
311
                                ++$j;
312
                                break;
313
                        }
314
                    } else {
315
                        $row[] = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
316
                    }
317
                }
318
            }
319
        }
320
        // ================= COMMA ================= //
321
        for ($i = 0; $i < $j; ++$i) {
322
            if ($i != $j - 1) {
323
                $row[] = $comma[$i] . ',';
324
            } else {
325
                $row[] = $comma[$i];
326
            }
327
        }
328
        // ================= COMMA CICLE ================= //
329
        $ret .= implode("\n", $row);
330
        unset($j);
331
        $ret .= $this->getFootDatabaseTable();
332
333
        return $ret;
334
    }
335
336
    /**
337
     * @private function getFootDatabaseTable
338
     *
339
     * @param null
340
     *
341
     * @return string
342
     */
343
    private function getFootDatabaseTable()
344
    {
345
        return "\n) ENGINE=InnoDB;\n\n";
346
    }
347
348
    /**
349
     * @private function getFieldRow
350
     *
351
     * @param $fieldName
352
     * @param $fieldTypeValue
353
     * @param $fieldAttribute
354
     * @param $fieldNull
355
     * @param $fieldDefault
356
     * @param $autoincrement
357
     *
358
     * @return string
359
     */
360
    private function getFieldRow($fieldName, $fieldTypeValue, $fieldAttribute = null, $fieldNull = null, $fieldDefault = null, $autoincrement = null)
361
    {
362
        $retAutoincrement  = "  `{$fieldName}` {$fieldTypeValue} {$fieldAttribute} {$fieldNull} {$autoincrement},";
363
        $retFieldAttribute = "  `{$fieldName}` {$fieldTypeValue} {$fieldAttribute} {$fieldNull} {$fieldDefault},";
364
        $fieldDefault      = "  `{$fieldName}` {$fieldTypeValue} {$fieldNull} {$fieldDefault},";
365
        $retShort          = "  `{$fieldName}` {$fieldTypeValue},";
366
367
        $ret = $retShort;
368
        if (null != $autoincrement) {
369
            $ret = $retAutoincrement;
370
        } elseif (null != $fieldAttribute) {
371
            $ret = $retFieldAttribute;
372
        } elseif (null === $fieldAttribute) {
373
            $ret = $fieldDefault;
374
        }
375
376
        return $ret;
377
    }
378
379
    /**
380
     * @private function getKey
381
     *
382
     * @param $key
383
     * @param $fieldName
384
     * @return string
385
     */
386
    private function getKey($key, $fieldName)
387
    {
388
        $ret = null;
389
        switch ($key) {
390
            case 2: // PRIMARY KEY
391
                $ret = "  PRIMARY KEY (`{$fieldName}`)";
392
                break;
393
            case 3: // UNIQUE KEY
394
                $ret = "  UNIQUE KEY `{$fieldName}` (`{$fieldName}`)";
395
                break;
396
            case 4: // KEY
397
                $ret = "  KEY `{$fieldName}` (`{$fieldName}`)";
398
                break;
399
            case 5: // INDEX
400
                $ret = "  INDEX (`{$fieldName}`)";
401
                break;
402
            case 6: // FULLTEXT KEY
403
                $ret = "  FULLTEXT KEY `{$fieldName}` (`{$fieldName}`)";
404
                break;
405
        }
406
407
        return $ret;
408
    }
409
410
    /**
411
     * @private function getComma
412
     *
413
     * @param $row
414
     * @param $comma
415
     *
416
     * @return string
417
     */
418
    private function getComma($row, $comma = null)
419
    {
420
        return " {$row}{$comma}";
421
    }
422
423
    /**
424
     * @private function getCommaCicle
425
     *
426
     * @param $comma
427
     * @param $index
428
     *
429
     * @return string
430
     */
431
    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...
432
    {
433
        $ret = null;
434
        // Comma issue
435
        for ($i = 1; $i <= $index; ++$i) {
436
            if ($i != $index - 1) {
437
                $ret = $this->getComma(isset($comma[$i]), ',') . "\n";
438
            } else {
439
                $ret = $this->getComma(isset($comma[$i])) . "\n";
440
            }
441
        }
442
443
        return $ret;
444
    }
445
446
    /**
447
     * @public function render
448
     *
449
     * @param null
450
     *
451
     * @return bool|string
452
     */
453
    public function render()
454
    {
455
        $module        = $this->getModule();
456
        $filename      = $this->getFileName();
457
        $moduleName    = mb_strtolower($module->getVar('mod_name'));
458
        $moduleDirname = mb_strtolower($module->getVar('mod_dirname'));
459
        $content       = $this->getHeaderSqlComments($moduleName);
460
        $content       .= $this->getDatabaseTables($module);
461
462
        $this->create($moduleDirname, 'sql', $filename, $content, _AM_TDMCREATE_FILE_CREATED, _AM_TDMCREATE_FILE_NOTCREATED);
463
464
        return $this->renderFile();
465
    }
466
}
467