Passed
Push — master ( 0c230a...202965 )
by Michael
02:53
created

SqlFile::getDatabaseFields()   F

Complexity

Conditions 47
Paths 6363

Size

Total Lines 167

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 47
nc 6363
nop 6
dl 0
loc 167
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
/*
4
 You may not change or alter any portion of this comment or credits
5
 of supporting developers from this source code or any supporting source code
6
 which is considered copyrighted (c) material of the original comment or credit authors.
7
8
 This program is distributed in the hope that it will be useful,
9
 but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11
 */
12
/**
13
 * tdmcreate module.
14
 *
15
 * @copyright       XOOPS Project (https://xoops.org)
16
 * @license         GNU GPL 2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)
17
 *
18
 * @since           2.5.0
19
 *
20
 * @author          Txmod Xoops http://www.txmodxoops.org
21
 *
22
 * @version         $Id: SqlFile.php 12258 2014-01-02 09:33:29Z timgno $
23
 */
24
25
/**
26
 * Class SqlFile.
27
 */
28
class SqlFile extends TDMCreateFile
29
{
30
    /**
31
     *  @public function constructor
32
     *
33
     *  @param null
34
     */
35
    public function __construct()
36
    {
37
        parent::__construct();
38
    }
39
40
    /**
41
     * @static function getInstance
42
     *
43
     * @param null
44
     *
45
     * @return SqlFile
46
     */
47
    public static function getInstance()
48
    {
49
        static $instance = false;
50
        if (!$instance) {
51
            $instance = new self();
52
        }
53
54
        return $instance;
55
    }
56
57
    /**
58
     *  @public function write
59
     *
60
     *  @param $module
61
     *  @param $filename
62
     */
63
    public function write($module, $filename)
64
    {
65
        $this->setModule($module);
66
        $this->setFileName($filename);
67
    }
68
69
    /**
70
     * @private function getHeaderSqlComments
71
     *
72
     * @param $moduleName
73
     *
74
     * @return string
75
     */
76
    private function getHeaderSqlComments($moduleName)
77
    {
78
        $date = date('D M d, Y');
79
        $time = date('H:i:s');
80
        $serverName = $_SERVER['SERVER_NAME'];
81
        $serverVersion = $GLOBALS['xoopsDB']->getServerVersion();
82
        $phpVersion = PHP_VERSION;
83
        // Header Sql Comments
84
        $ret = null;
85
        $arrayServerInfo = [
86
            "# SQL Dump for {$moduleName} module", '# PhpMyAdmin Version: 4.0.4',
87
            '# http://www.phpmyadmin.net', '#', "# Host: {$serverName}",
88
            "# Generated on: {$date} to {$time}", "# Server version: {$serverVersion}",
89
            "# PHP Version: {$phpVersion}\n",
90
        ];
91
        foreach ($arrayServerInfo as $serverInfo) {
92
            $ret .= $this->getSimpleString($serverInfo);
93
        }
94
95
        return $ret;
96
    }
97
98
    /**
99
     *  @private function getHeadDatabaseTable
100
     *  @param $moduleDirname
101
     *  @param $tableName
102
     *  @param int $fieldsNumb
103
     *
104
     *  Unused IF NOT EXISTS
105
     *
106
     *  @return string
107
     */
108
    private function getHeadDatabaseTable($moduleDirname, $tableName, $fieldsNumb)
109
    {
110
        $ret = null;
111
        $arrayDbTable = [
112
            '#', "# Structure table for `{$moduleDirname}_{$tableName}` {$fieldsNumb}",
113
            '#', "\nCREATE TABLE `{$moduleDirname}_{$tableName}` (",
114
        ];
115
        foreach ($arrayDbTable as $dbTable) {
116
            $ret .= $this->getSimpleString($dbTable);
117
        }
118
119
        return $ret;
120
    }
121
122
    /**
123
     *  @private function getDatabaseTables
124
     *
125
     *  @param $module
126
     *
127
     *  @return null|string
128
     */
129
    private function getDatabaseTables($module)
130
    {
131
        $ret = null;
132
        $moduleDirname = mb_strtolower($module->getVar('mod_dirname'));
133
        $tables = $this->getTableTables($module->getVar('mod_id'), 'table_order ASC, table_id');
134
        foreach (array_keys($tables) as $t) {
135
            $tableId = $tables[$t]->getVar('table_id');
136
            $tableMid = $tables[$t]->getVar('table_mid');
137
            $tableName = $tables[$t]->getVar('table_name');
138
            $tableAutoincrement = $tables[$t]->getVar('table_autoincrement');
139
            $fieldsNumb = $tables[$t]->getVar('table_nbfields');
140
            $ret .= $this->getDatabaseFields($moduleDirname, $tableMid, $tableId, $tableName, $tableAutoincrement, $fieldsNumb);
141
        }
142
143
        return $ret;
144
    }
145
146
    /**
147
     * @private function getDatabaseFields
148
     *
149
     * @param $moduleDirname
150
     * @param $tableMid
151
     * @param $tableId
152
     * @param $tableName
153
     * @param $tableAutoincrement
154
     * @param $fieldsNumb
155
     * @return null|string
156
     */
157
    private function getDatabaseFields($moduleDirname, $tableMid, $tableId, $tableName, $tableAutoincrement, $fieldsNumb)
158
    {
159
        $tdmcreate = TDMCreateHelper::getInstance();
160
        $ret = null;
161
        $j = 0;
162
        $comma = [];
163
        $row = [];
164
        $type = '';
0 ignored issues
show
Unused Code introduced by
$type is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
165
        $fields = $this->getTableFields($tableMid, $tableId, 'field_id ASC, field_name');
166
        foreach (array_keys($fields) as $f) {
167
            // Creation of database table
168
            $ret = $this->getHeadDatabaseTable($moduleDirname, $tableName, $fieldsNumb);
169
            $fieldName = $fields[$f]->getVar('field_name');
170
            $fieldType = $fields[$f]->getVar('field_type');
171
            $fieldValue = $fields[$f]->getVar('field_value');
172
            $fieldAttribute = $fields[$f]->getVar('field_attribute');
173
            $fieldNull = $fields[$f]->getVar('field_null');
174
            $fieldDefault = $fields[$f]->getVar('field_default');
175
            $fieldKey = $fields[$f]->getVar('field_key');
176
            if ($fieldType > 1) {
177
                $fType = $tdmcreate->getHandler('fieldtype')->get($fieldType);
0 ignored issues
show
Bug introduced by
The method get cannot be called on $tdmcreate->getHandler('fieldtype') (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
178
                $fieldTypeName = $fType->getVar('fieldtype_name');
179
            } else {
180
                $fieldType = null;
181
            }
182
            if ($fieldAttribute > 1) {
183
                $fAttribute = $tdmcreate->getHandler('fieldattributes')->get($fieldAttribute);
0 ignored issues
show
Bug introduced by
The method get cannot be called on $tdmcreate->getHandler('fieldattributes') (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
184
                $fieldAttribute = $fAttribute->getVar('fieldattribute_name');
185
            } else {
186
                $fieldAttribute = null;
187
            }
188
            if ($fieldNull > 1) {
189
                $fNull = $tdmcreate->getHandler('fieldnull')->get($fieldNull);
0 ignored issues
show
Bug introduced by
The method get cannot be called on $tdmcreate->getHandler('fieldnull') (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
190
                $fieldNull = $fNull->getVar('fieldnull_name');
191
            } else {
192
                $fieldNull = null;
193
            }
194
            if (!empty($fieldName)) {
195
                switch ($fieldType) {
196
                    case 2:
197
                    case 3:
198
                    case 4:
199
                    case 5:
200
                        $type = $fieldTypeName . '(' . $fieldValue . ')';
0 ignored issues
show
Bug introduced by
The variable $fieldTypeName does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
201
                        if (empty($fieldDefault)) {
202
                            $default = "DEFAULT '0'";
203
                        } else {
204
                            $default = "DEFAULT '{$fieldDefault}'";
205
                        }
206
                        break;
207
                    case 6:
208
                    case 7:
209
                    case 8:
210
                        $type = $fieldTypeName . '(' . $fieldValue . ')';
211
                        if (empty($fieldDefault)) {
212
                            $default = "DEFAULT '0.00'"; // From MySQL 5.7 Manual
213
                        } else {
214
                            $default = "DEFAULT '{$fieldDefault}'";
215
                        }
216
                        break;
217
                    case 9:
218
                    case 10:
219
                        $fValues = implode("', '", explode(',', str_replace(' ', '', $fieldValue)));
220
                        $type = $fieldTypeName . '(\'' . $fValues . '\')'; // Used with comma separator
221
                        $default = "DEFAULT '{$fieldDefault}'";
222
                        break;
223
                    case 11:
224
                        $type = $fieldTypeName . '(' . $fieldValue . ')';
225
                        if (empty($fieldDefault)) {
226
                            $default = "DEFAULT '[email protected]'";
227
                        } else {
228
                            $default = "DEFAULT '{$fieldDefault}'";
229
                        }
230
                        break;
231
                    case 12:
232
                        $type = $fieldTypeName . '(' . $fieldValue . ')';
233
                        if (empty($fieldDefault)) {
234
                            $default = "DEFAULT 'http:\\'";
235
                        } else {
236
                            $default = "DEFAULT '{$fieldDefault}'";
237
                        }
238
                        break;
239
                    case 13:
240
                    case 14:
241
                        $type = $fieldTypeName . '(' . $fieldValue . ')';
242
                        $default = "DEFAULT '{$fieldDefault}'";
243
                        break;
244
                    case 15:
245
                    case 16:
246
                    case 17:
247
                    case 18:
248
                        $type = $fieldTypeName;
249
                        $default = null;
250
                        break;
251
                    case 19:
252
                    case 20:
253
                    case 21:
254
                    case 22:
255
                        $type = $fieldTypeName . '(' . $fieldValue . ')';
256
                        $default = "DEFAULT '{$fieldDefault}'";
257
                        break;
258
                    case 23:
259
                        $type = $fieldTypeName;
260
                        if (empty($fieldDefault)) {
261
                            $default = "DEFAULT '1970'"; // From MySQL 5.7 Manual
262
                        } else {
263
                            $default = "DEFAULT '{$fieldDefault}'";
264
                        }
265
                        break;
266
                    default:
267
                        $type = $fieldTypeName . '(' . $fieldValue . ')';
268
                        $default = "DEFAULT '{$fieldDefault}'";
269
                        break;
270
                }
271
                if ((0 == $f) && (1 == $tableAutoincrement)) {
272
                    $row[] = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, null, 'AUTO_INCREMENT');
273
                    $comma[$j] = $this->getKey(2, $fieldName);
274
                    ++$j;
275
                } elseif ((0 == $f) && (0 == $tableAutoincrement)) {
276
                    $row[] = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
277
                    $comma[$j] = $this->getKey(2, $fieldName);
278
                    ++$j;
279
                } else {
280
                    if (3 == $fieldKey || 4 == $fieldKey || 5 == $fieldKey || 6 == $fieldKey) {
281
                        switch ($fieldKey) {
282
                            case 3:
283
                                $row[] = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
284
                                $comma[$j] = $this->getKey(3, $fieldName);
285
                                ++$j;
286
                                break;
287
                            case 4:
288
                                $row[] = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
289
                                $comma[$j] = $this->getKey(4, $fieldName);
290
                                ++$j;
291
                                break;
292
                            case 5:
293
                                $row[] = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
294
                                $comma[$j] = $this->getKey(5, $fieldName);
295
                                ++$j;
296
                                break;
297
                            case 6:
298
                                $row[] = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
299
                                $comma[$j] = $this->getKey(6, $fieldName);
300
                                ++$j;
301
                                break;
302
                        }
303
                    } else {
304
                        $row[] = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
305
                    }
306
                }
307
            }
308
        }
309
        // ================= COMMA ================= //
310
        for ($i = 0; $i < $j; ++$i) {
311
            if ($i != $j - 1) {
312
                $row[] = $comma[$i] . ',';
313
            } else {
314
                $row[] = $comma[$i];
315
            }
316
        }
317
        // ================= COMMA CICLE ================= //
318
        $ret .= implode("\n", $row);
319
        unset($j);
320
        $ret .= $this->getFootDatabaseTable();
321
322
        return $ret;
323
    }
324
325
    /**
326
     *  @private function getFootDatabaseTable
327
     *
328
     *  @param null
329
     *
330
     * @return string
331
     */
332
    private function getFootDatabaseTable()
333
    {
334
        return "\n) ENGINE=InnoDB;\n\n";
335
    }
336
337
    /**
338
     *  @private function getFieldRow
339
     *
340
     *  @param $fieldName
341
     *  @param $fieldTypeValue
342
     *  @param $fieldAttribute
343
     *  @param $fieldNull
344
     *  @param $fieldDefault
345
     *  @param $autoincrement
346
     *
347
     *  @return string
348
     */
349
    private function getFieldRow($fieldName, $fieldTypeValue, $fieldAttribute = null, $fieldNull = null, $fieldDefault = null, $autoincrement = null)
350
    {
351
        $retAutoincrement = "  `{$fieldName}` {$fieldTypeValue} {$fieldAttribute} {$fieldNull} {$autoincrement},";
352
        $retFieldAttribute = "  `{$fieldName}` {$fieldTypeValue} {$fieldAttribute} {$fieldNull} {$fieldDefault},";
353
        $fieldDefault = "  `{$fieldName}` {$fieldTypeValue} {$fieldNull} {$fieldDefault},";
354
        $retShort = "  `{$fieldName}` {$fieldTypeValue},";
355
356
        $ret = $retShort;
357
        if (null != $autoincrement) {
358
            $ret = $retAutoincrement;
359
        } elseif (null != $fieldAttribute) {
360
            $ret = $retFieldAttribute;
361
        } elseif (null === $fieldAttribute) {
362
            $ret = $fieldDefault;
363
        }
364
365
        return $ret;
366
    }
367
368
    /**
369
     * @private function getKey
370
     *
371
     * @param $key
372
     * @param $fieldName
373
     * @return string
374
     */
375
    private function getKey($key, $fieldName)
376
    {
377
        $ret = null;
378
        switch ($key) {
379
            case 2: // PRIMARY KEY
380
                $ret = "  PRIMARY KEY (`{$fieldName}`)";
381
                break;
382
            case 3: // UNIQUE KEY
383
                $ret = "  UNIQUE KEY `{$fieldName}` (`{$fieldName}`)";
384
                break;
385
            case 4: // KEY
386
                $ret = "  KEY `{$fieldName}` (`{$fieldName}`)";
387
                break;
388
            case 5: // INDEX
389
                $ret = "  INDEX (`{$fieldName}`)";
390
                break;
391
            case 6: // FULLTEXT KEY
392
                $ret = "  FULLTEXT KEY `{$fieldName}` (`{$fieldName}`)";
393
                break;
394
        }
395
396
        return $ret;
397
    }
398
399
    /**
400
     *  @private function getComma
401
     *
402
     *  @param $row
403
     *  @param $comma
404
     *
405
     *  @return string
406
     */
407
    private function getComma($row, $comma = null)
408
    {
409
        return " {$row}{$comma}";
410
    }
411
412
    /**
413
     *  @private function getCommaCicle
414
     *
415
     *  @param $comma
416
     *  @param $index
417
     *
418
     *  @return string
419
     */
420
    private function getCommaCicle($comma, $index)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
421
    {
422
        $ret = null;
423
        // Comma issue
424
        for ($i = 1; $i <= $index; ++$i) {
425
            if ($i != $index - 1) {
426
                $ret = $this->getComma(isset($comma[$i]), ',') . "\n";
427
            } else {
428
                $ret = $this->getComma(isset($comma[$i])) . "\n";
429
            }
430
        }
431
432
        return $ret;
433
    }
434
435
    /**
436
     *  @public function render
437
     *
438
     *  @param null
439
     *
440
     *  @return bool|string
441
     */
442
    public function render()
443
    {
444
        $module = $this->getModule();
445
        $filename = $this->getFileName();
446
        $moduleName = mb_strtolower($module->getVar('mod_name'));
447
        $moduleDirname = mb_strtolower($module->getVar('mod_dirname'));
448
        $content = $this->getHeaderSqlComments($moduleName);
449
        $content .= $this->getDatabaseTables($module);
450
451
        $this->create($moduleDirname, 'sql', $filename, $content, _AM_TDMCREATE_FILE_CREATED, _AM_TDMCREATE_FILE_NOTCREATED);
452
453
        return $this->renderFile();
454
    }
455
}
456