Passed
Push — master ( c14394...753352 )
by Goffy
04:41
created

SqlFile::getTableRatings()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 35
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 24
nc 3
nop 6
dl 0
loc 35
rs 9.536
c 0
b 0
f 0
1
<?php
2
3
namespace XoopsModules\Modulebuilder\Files\Sql;
4
5
use XoopsModules\Modulebuilder;
6
use XoopsModules\Modulebuilder\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
 * modulebuilder 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
        $tableRate     = 0;
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
            if (1 === (int)$tables[$t]->getVar('table_rate')) {
152
                $tableRate = 1;
153
            }
154
            $ret .= $this->getDatabaseFields($moduleDirname, $tableMid, $tableId, $tableName, $tableAutoincrement, $fieldsNumb);
155
        }
156
157
        if (1 === $tableRate) {
158
            $ret .= $this->getTableRatings($moduleDirname, $tableMid, $tableId, $tableName, $tableAutoincrement, $fieldsNumb);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $tableId seems to be defined by a foreach iteration on line 145. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
Comprehensibility Best Practice introduced by
The variable $tableName seems to be defined by a foreach iteration on line 145. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
Comprehensibility Best Practice introduced by
The variable $tableAutoincrement seems to be defined by a foreach iteration on line 145. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
Comprehensibility Best Practice introduced by
The variable $fieldsNumb seems to be defined by a foreach iteration on line 145. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
Comprehensibility Best Practice introduced by
The variable $tableMid seems to be defined by a foreach iteration on line 145. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
159
        }
160
161
        return $ret;
162
    }
163
164
    /**
165
     * @private function getDatabaseFields
166
     *
167
     * @param $moduleDirname
168
     * @param $tableMid
169
     * @param $tableId
170
     * @param $tableName
171
     * @param $tableAutoincrement
172
     * @param $fieldsNumb
173
     * @return null|string
174
     */
175
    private function getDatabaseFields($moduleDirname, $tableMid, $tableId, $tableName, $tableAutoincrement, $fieldsNumb)
176
    {
177
        $helper        = Modulebuilder\Helper::getInstance();
178
        $ret           = null;
179
        $j             = 0;
180
        $comma         = [];
181
        $row           = [];
182
        //$type          = '';
183
        $fieldTypeName = '';
184
        $fields = $this->getTableFields($tableMid, $tableId, 'field_id ASC, field_name');
185
        foreach (array_keys($fields) as $f) {
186
            // Creation of database table
187
            $ret            = $this->getHeadDatabaseTable($moduleDirname, $tableName, $fieldsNumb);
188
            $fieldName      = $fields[$f]->getVar('field_name');
189
            $fieldType      = $fields[$f]->getVar('field_type');
190
            $fieldValue     = str_replace('&#039;','', $fields[$f]->getVar('field_value')); //remove single quotes
191
            $fieldAttribute = $fields[$f]->getVar('field_attribute');
192
            $fieldNull      = $fields[$f]->getVar('field_null');
193
            $fieldDefault   = str_replace('&#039;','', $fields[$f]->getVar('field_default')); //remove single quotes
194
            $fieldKey       = $fields[$f]->getVar('field_key');
195
            if ($fieldType > 1) {
196
                $fType         = $helper->getHandler('Fieldtype')->get($fieldType);
197
                $fieldTypeName = $fType->getVar('fieldtype_name');
198
            } else {
199
                $fieldType = null;
200
            }
201
            if ($fieldAttribute > 1) {
202
                $fAttribute     = $helper->getHandler('Fieldattributes')->get($fieldAttribute);
203
                $fieldAttribute = $fAttribute->getVar('fieldattribute_name');
204
            } else {
205
                $fieldAttribute = null;
206
            }
207
            if ($fieldNull > 1) {
208
                $fNull     = $helper->getHandler('Fieldnull')->get($fieldNull);
209
                $fieldNull = $fNull->getVar('fieldnull_name');
210
            } else {
211
                $fieldNull = null;
212
            }
213
            if (!empty($fieldName)) {
214
                switch ($fieldType) {
215
                    case 2:
216
                    case 3:
217
                    case 4:
218
                    case 5:
219
                        $type = $fieldTypeName . '(' . $fieldValue . ')';
220
                        if (empty($fieldDefault)) {
221
                            $default = "DEFAULT '0'";
222
                        } else {
223
                            $default = "DEFAULT '{$fieldDefault}'";
224
                        }
225
                        break;
226
                    case 6:
227
                    case 7:
228
                    case 8:
229
                        $type = $fieldTypeName . '(' . $fieldValue . ')';
230
                        if (empty($fieldDefault)) {
231
                            $default = "DEFAULT '0'"; // From MySQL 5.7 Manual
232
                        } else {
233
                            $default = "DEFAULT '{$fieldDefault}'";
234
                        }
235
                        break;
236
                    case 9:
237
                    case 10:
238
                        $fValues = str_replace(',', "', '", str_replace(' ', '', $fieldValue));
239
                        $type    = $fieldTypeName . '(\'' . $fValues . '\')'; // Used with comma separator
240
                        $default = "DEFAULT '{$fieldDefault}'";
241
                        break;
242
                    case 11:
243
                        $type = $fieldTypeName . '(' . $fieldValue . ')';
244
                        if (empty($fieldDefault)) {
245
                            $default = "DEFAULT '[email protected]'";
246
                        } else {
247
                            $default = "DEFAULT '{$fieldDefault}'";
248
                        }
249
                        break;
250
                    case 12:
251
                        $type = $fieldTypeName . '(' . $fieldValue . ')';
252
                        if (empty($fieldDefault)) {
253
                            $default = "DEFAULT 'http:\\'";
254
                        } else {
255
                            $default = "DEFAULT '{$fieldDefault}'";
256
                        }
257
                        break;
258
                    case 13:
259
                    case 14:
260
                        $type    = $fieldTypeName . '(' . $fieldValue . ')';
261
                        $default = "DEFAULT '{$fieldDefault}'";
262
                        break;
263
                    case 15:
264
                    case 16:
265
                    case 17:
266
                    case 18:
267
                        $type    = $fieldTypeName;
268
                        $default = null;
269
                        break;
270
                    case 19:
271
                    case 20:
272
                    case 21:
273
                    case 22:
274
                        $type    = $fieldTypeName . '(' . $fieldValue . ')';
275
                        $default = "DEFAULT '{$fieldDefault}'";
276
                        break;
277
                    case 23:
278
                        $type = $fieldTypeName;
279
                        if (empty($fieldDefault)) {
280
                            $default = "DEFAULT '1970'"; // From MySQL 5.7 Manual
281
                        } else {
282
                            $default = "DEFAULT '{$fieldDefault}'";
283
                        }
284
                        break;
285
                    default:
286
                        $type    = $fieldTypeName . '(' . $fieldValue . ')';
287
                        $default = "DEFAULT '{$fieldDefault}'";
288
                        break;
289
                }
290
                if ((0 == $f) && (1 == $tableAutoincrement)) {
291
                    $row[]     = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, null, 'AUTO_INCREMENT');
292
                    $comma[$j] = $this->getKey(2, $fieldName);
293
                    ++$j;
294
                } elseif ((0 == $f) && (0 == $tableAutoincrement)) {
295
                    $row[]     = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
296
                    $comma[$j] = $this->getKey(2, $fieldName);
297
                    ++$j;
298
                } else {
299
                    if (3 == $fieldKey || 4 == $fieldKey || 5 == $fieldKey || 6 == $fieldKey) {
300
                        switch ($fieldKey) {
301
                            case 3:
302
                                $row[]     = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
303
                                $comma[$j] = $this->getKey(3, $fieldName);
304
                                ++$j;
305
                                break;
306
                            case 4:
307
                                $row[]     = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
308
                                $comma[$j] = $this->getKey(4, $fieldName);
309
                                ++$j;
310
                                break;
311
                            case 5:
312
                                $row[]     = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
313
                                $comma[$j] = $this->getKey(5, $fieldName);
314
                                ++$j;
315
                                break;
316
                            case 6:
317
                                $row[]     = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
318
                                $comma[$j] = $this->getKey(6, $fieldName);
319
                                ++$j;
320
                                break;
321
                        }
322
                    } else {
323
                        $row[] = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
324
                    }
325
                }
326
            }
327
        }
328
        // ================= COMMA ================= //
329
        for ($i = 0; $i < $j; ++$i) {
330
            if ($i != $j - 1) {
331
                $row[] = $comma[$i] . ',';
332
            } else {
333
                $row[] = $comma[$i];
334
            }
335
        }
336
        // ================= COMMA CICLE ================= //
337
        $ret .= implode("\n", $row);
338
        unset($j);
339
        $ret .= $this->getFootDatabaseTable();
340
341
        return $ret;
342
    }
343
344
    /**
345
     * @private function getDatabaseFields
346
     *
347
     * @param $moduleDirname
348
     * @param $tableMid
349
     * @param $tableId
350
     * @param $tableName
351
     * @param $tableAutoincrement
352
     * @param $fieldsNumb
353
     * @return null|string
354
     */
355
    private function getTableRatings($moduleDirname, $tableMid, $tableId, $tableName, $tableAutoincrement, $fieldsNumb)
0 ignored issues
show
Unused Code introduced by
The parameter $tableAutoincrement is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

355
    private function getTableRatings($moduleDirname, $tableMid, $tableId, $tableName, /** @scrutinizer ignore-unused */ $tableAutoincrement, $fieldsNumb)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $fieldsNumb is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

355
    private function getTableRatings($moduleDirname, $tableMid, $tableId, $tableName, $tableAutoincrement, /** @scrutinizer ignore-unused */ $fieldsNumb)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $tableMid is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

355
    private function getTableRatings($moduleDirname, /** @scrutinizer ignore-unused */ $tableMid, $tableId, $tableName, $tableAutoincrement, $fieldsNumb)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $tableName is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

355
    private function getTableRatings($moduleDirname, $tableMid, $tableId, /** @scrutinizer ignore-unused */ $tableName, $tableAutoincrement, $fieldsNumb)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $tableId is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

355
    private function getTableRatings($moduleDirname, $tableMid, /** @scrutinizer ignore-unused */ $tableId, $tableName, $tableAutoincrement, $fieldsNumb)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
356
    {
357
        $helper        = Modulebuilder\Helper::getInstance();
0 ignored issues
show
Unused Code introduced by
The assignment to $helper is dead and can be removed.
Loading history...
358
        $ret           = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $ret is dead and can be removed.
Loading history...
359
        $j             = 0;
360
        $comma         = [];
361
        $row           = [];
362
363
        $ret            = $this->getHeadDatabaseTable($moduleDirname, 'ratings', 6);
364
        //$row[] = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
365
        $row[] = $this->getFieldRow('rate_id', 'INT(8)', 'UNSIGNED', 'NOT NULL', null, 'AUTO_INCREMENT');
366
        $comma[$j] = $this->getKey(2, 'rate_id');
367
        ++$j;
368
        $row[] = $this->getFieldRow('rate_itemid', 'INT(8)', null, 'NOT NULL', "DEFAULT '0'");
369
        $row[] = $this->getFieldRow('rate_source', 'INT(8)', null, 'NOT NULL', "DEFAULT '0'");
370
        $row[] = $this->getFieldRow('rate_value', 'INT(1)', null, 'NOT NULL', "DEFAULT '0'");
371
        $row[] = $this->getFieldRow('rate_uid', 'INT(8)', null, 'NOT NULL', "DEFAULT '0'");
372
        $row[] = $this->getFieldRow('rate_ip', 'VARCHAR(60)', null, 'NOT NULL', "DEFAULT ''");
373
        $row[] = $this->getFieldRow('rate_date', 'INT(8)', null, 'NOT NULL', "DEFAULT '0'");
374
375
376
        // ================= COMMA ================= //
377
        for ($i = 0; $i < $j; ++$i) {
378
            if ($i != $j - 1) {
379
                $row[] = $comma[$i] . ',';
380
            } else {
381
                $row[] = $comma[$i];
382
            }
383
        }
384
        // ================= COMMA CICLE ================= //
385
        $ret .= implode("\n", $row);
386
        unset($j);
387
        $ret .= $this->getFootDatabaseTable();
388
389
        return $ret;
390
    }
391
392
    /**
393
     * @private function getFootDatabaseTable
394
     *
395
     * @param null
396
     *
397
     * @return string
398
     */
399
    private function getFootDatabaseTable()
400
    {
401
        return "\n) ENGINE=InnoDB;\n\n";
402
    }
403
404
    /**
405
     * @private function getFieldRow
406
     *
407
     * @param $fieldName
408
     * @param $fieldTypeValue
409
     * @param $fieldAttribute
410
     * @param $fieldNull
411
     * @param $fieldDefault
412
     * @param $autoincrement
413
     *
414
     * @return string
415
     */
416
    private function getFieldRow($fieldName, $fieldTypeValue, $fieldAttribute = null, $fieldNull = null, $fieldDefault = null, $autoincrement = null)
417
    {
418
        $retAutoincrement  = "  `{$fieldName}` {$fieldTypeValue} {$fieldAttribute} {$fieldNull} {$autoincrement},";
419
        $retFieldAttribute = "  `{$fieldName}` {$fieldTypeValue} {$fieldAttribute} {$fieldNull} {$fieldDefault},";
420
        $fieldDefault      = "  `{$fieldName}` {$fieldTypeValue} {$fieldNull} {$fieldDefault},";
421
        $retShort          = "  `{$fieldName}` {$fieldTypeValue},";
422
423
        $ret = $retShort;
424
        if (null != $autoincrement) {
425
            $ret = $retAutoincrement;
426
        } elseif (null != $fieldAttribute) {
427
            $ret = $retFieldAttribute;
428
        } elseif (null === $fieldAttribute) {
429
            $ret = $fieldDefault;
430
        }
431
432
        return $ret;
433
    }
434
435
    /**
436
     * @private function getKey
437
     *
438
     * @param $key
439
     * @param $fieldName
440
     * @return string
441
     */
442
    private function getKey($key, $fieldName)
443
    {
444
        $ret = null;
445
        switch ($key) {
446
            case 2: // PRIMARY KEY
447
                $ret = "  PRIMARY KEY (`{$fieldName}`)";
448
                break;
449
            case 3: // UNIQUE KEY
450
                $ret = "  UNIQUE KEY `{$fieldName}` (`{$fieldName}`)";
451
                break;
452
            case 4: // KEY
453
                $ret = "  KEY `{$fieldName}` (`{$fieldName}`)";
454
                break;
455
            case 5: // INDEX
456
                $ret = "  INDEX (`{$fieldName}`)";
457
                break;
458
            case 6: // FULLTEXT KEY
459
                $ret = "  FULLTEXT KEY `{$fieldName}` (`{$fieldName}`)";
460
                break;
461
        }
462
463
        return $ret;
464
    }
465
466
    /**
467
     * @private function getComma
468
     *
469
     * @param $row
470
     * @param $comma
471
     *
472
     * @return string
473
     */
474
    private function getComma($row, $comma = null)
0 ignored issues
show
Unused Code introduced by
The method getComma() 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...
475
    {
476
        return " {$row}{$comma}";
477
    }
478
479
    /**
480
     * @public function render
481
     *
482
     * @param null
483
     *
484
     * @return bool|string
485
     */
486
    public function render()
487
    {
488
        $module        = $this->getModule();
489
        $filename      = $this->getFileName();
490
        $moduleName    = mb_strtolower($module->getVar('mod_name'));
491
        $moduleDirname = mb_strtolower($module->getVar('mod_dirname'));
492
        $content       = $this->getHeaderSqlComments($moduleName);
493
        $content       .= $this->getDatabaseTables($module);
494
495
        $this->create($moduleDirname, 'sql', $filename, $content, _AM_MODULEBUILDER_FILE_CREATED, _AM_MODULEBUILDER_FILE_NOTCREATED);
496
497
        return $this->renderFile();
498
    }
499
}
500