Passed
Push — master ( 753352...529310 )
by Goffy
04:13
created

SqlFile::getComma()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 3
rs 10
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
        $tableMid           = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $tableMid is dead and can be removed.
Loading history...
145
        $tableId            = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $tableId is dead and can be removed.
Loading history...
146
        $tableName          = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $tableName is dead and can be removed.
Loading history...
147
        $tableAutoincrement = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $tableAutoincrement is dead and can be removed.
Loading history...
148
        $fieldsNumb         = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $fieldsNumb is dead and can be removed.
Loading history...
149
        $tableRate          = 0;
150
        foreach (array_keys($tables) as $t) {
151
            $tableId            = $tables[$t]->getVar('table_id');
152
            $tableMid           = $tables[$t]->getVar('table_mid');
153
            $tableName          = $tables[$t]->getVar('table_name');
154
            $tableAutoincrement = $tables[$t]->getVar('table_autoincrement');
155
            $fieldsNumb         = $tables[$t]->getVar('table_nbfields');
156
            if (1 === (int)$tables[$t]->getVar('table_rate')) {
157
                $tableRate = 1;
158
            }
159
            $ret .= $this->getDatabaseFields($moduleDirname, $tableMid, $tableId, $tableName, $tableAutoincrement, $fieldsNumb);
160
        }
161
162
        if (1 === $tableRate) {
163
            $ret .= $this->getTableRatings($moduleDirname);
164
        }
165
166
        return $ret;
167
    }
168
169
    /**
170
     * @private function getDatabaseFields
171
     *
172
     * @param $moduleDirname
173
     * @param $tableMid
174
     * @param $tableId
175
     * @param $tableName
176
     * @param $tableAutoincrement
177
     * @param $fieldsNumb
178
     * @return null|string
179
     */
180
    private function getDatabaseFields($moduleDirname, $tableMid, $tableId, $tableName, $tableAutoincrement, $fieldsNumb)
181
    {
182
        $helper        = Modulebuilder\Helper::getInstance();
183
        $ret           = null;
184
        $j             = 0;
185
        $comma         = [];
186
        $row           = [];
187
        //$type          = '';
188
        $fieldTypeName = '';
189
        $fields = $this->getTableFields($tableMid, $tableId, 'field_id ASC, field_name');
190
        foreach (array_keys($fields) as $f) {
191
            // Creation of database table
192
            $ret            = $this->getHeadDatabaseTable($moduleDirname, $tableName, $fieldsNumb);
193
            $fieldName      = $fields[$f]->getVar('field_name');
194
            $fieldType      = $fields[$f]->getVar('field_type');
195
            $fieldValue     = str_replace('&#039;','', $fields[$f]->getVar('field_value')); //remove single quotes
196
            $fieldAttribute = $fields[$f]->getVar('field_attribute');
197
            $fieldNull      = $fields[$f]->getVar('field_null');
198
            $fieldDefault   = str_replace('&#039;','', $fields[$f]->getVar('field_default')); //remove single quotes
199
            $fieldKey       = $fields[$f]->getVar('field_key');
200
            if ($fieldType > 1) {
201
                $fType         = $helper->getHandler('Fieldtype')->get($fieldType);
202
                $fieldTypeName = $fType->getVar('fieldtype_name');
203
            } else {
204
                $fieldType = null;
205
            }
206
            if ($fieldAttribute > 1) {
207
                $fAttribute     = $helper->getHandler('Fieldattributes')->get($fieldAttribute);
208
                $fieldAttribute = $fAttribute->getVar('fieldattribute_name');
209
            } else {
210
                $fieldAttribute = null;
211
            }
212
            if ($fieldNull > 1) {
213
                $fNull     = $helper->getHandler('Fieldnull')->get($fieldNull);
214
                $fieldNull = $fNull->getVar('fieldnull_name');
215
            } else {
216
                $fieldNull = null;
217
            }
218
            if (!empty($fieldName)) {
219
                switch ($fieldType) {
220
                    case 2:
221
                    case 3:
222
                    case 4:
223
                    case 5:
224
                        $type = $fieldTypeName . '(' . $fieldValue . ')';
225
                        if (empty($fieldDefault)) {
226
                            $default = "DEFAULT '0'";
227
                        } else {
228
                            $default = "DEFAULT '{$fieldDefault}'";
229
                        }
230
                        break;
231
                    case 6:
232
                    case 7:
233
                    case 8:
234
                        $type = $fieldTypeName . '(' . $fieldValue . ')';
235
                        if (empty($fieldDefault)) {
236
                            $default = "DEFAULT '0'"; // From MySQL 5.7 Manual
237
                        } else {
238
                            $default = "DEFAULT '{$fieldDefault}'";
239
                        }
240
                        break;
241
                    case 9:
242
                    case 10:
243
                        $fValues = str_replace(',', "', '", str_replace(' ', '', $fieldValue));
244
                        $type    = $fieldTypeName . '(\'' . $fValues . '\')'; // Used with comma separator
245
                        $default = "DEFAULT '{$fieldDefault}'";
246
                        break;
247
                    case 11:
248
                        $type = $fieldTypeName . '(' . $fieldValue . ')';
249
                        if (empty($fieldDefault)) {
250
                            $default = "DEFAULT '[email protected]'";
251
                        } else {
252
                            $default = "DEFAULT '{$fieldDefault}'";
253
                        }
254
                        break;
255
                    case 12:
256
                        $type = $fieldTypeName . '(' . $fieldValue . ')';
257
                        if (empty($fieldDefault)) {
258
                            $default = "DEFAULT 'http:\\'";
259
                        } else {
260
                            $default = "DEFAULT '{$fieldDefault}'";
261
                        }
262
                        break;
263
                    case 13:
264
                    case 14:
265
                        $type    = $fieldTypeName . '(' . $fieldValue . ')';
266
                        $default = "DEFAULT '{$fieldDefault}'";
267
                        break;
268
                    case 15:
269
                    case 16:
270
                    case 17:
271
                    case 18:
272
                        $type    = $fieldTypeName;
273
                        $default = null;
274
                        break;
275
                    case 19:
276
                    case 20:
277
                    case 21:
278
                    case 22:
279
                        $type    = $fieldTypeName . '(' . $fieldValue . ')';
280
                        $default = "DEFAULT '{$fieldDefault}'";
281
                        break;
282
                    case 23:
283
                        $type = $fieldTypeName;
284
                        if (empty($fieldDefault)) {
285
                            $default = "DEFAULT '1970'"; // From MySQL 5.7 Manual
286
                        } else {
287
                            $default = "DEFAULT '{$fieldDefault}'";
288
                        }
289
                        break;
290
                    default:
291
                        $type    = $fieldTypeName . '(' . $fieldValue . ')';
292
                        $default = "DEFAULT '{$fieldDefault}'";
293
                        break;
294
                }
295
                if ((0 == $f) && (1 == $tableAutoincrement)) {
296
                    $row[]     = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, null, 'AUTO_INCREMENT');
297
                    $comma[$j] = $this->getKey(2, $fieldName);
298
                    ++$j;
299
                } elseif ((0 == $f) && (0 == $tableAutoincrement)) {
300
                    $row[]     = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
301
                    $comma[$j] = $this->getKey(2, $fieldName);
302
                    ++$j;
303
                } else {
304
                    if (3 == $fieldKey || 4 == $fieldKey || 5 == $fieldKey || 6 == $fieldKey) {
305
                        switch ($fieldKey) {
306
                            case 3:
307
                                $row[]     = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
308
                                $comma[$j] = $this->getKey(3, $fieldName);
309
                                ++$j;
310
                                break;
311
                            case 4:
312
                                $row[]     = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
313
                                $comma[$j] = $this->getKey(4, $fieldName);
314
                                ++$j;
315
                                break;
316
                            case 5:
317
                                $row[]     = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
318
                                $comma[$j] = $this->getKey(5, $fieldName);
319
                                ++$j;
320
                                break;
321
                            case 6:
322
                                $row[]     = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
323
                                $comma[$j] = $this->getKey(6, $fieldName);
324
                                ++$j;
325
                                break;
326
                        }
327
                    } else {
328
                        $row[] = $this->getFieldRow($fieldName, $type, $fieldAttribute, $fieldNull, $default);
329
                    }
330
                }
331
            }
332
        }
333
        // ================= COMMA ================= //
334
        for ($i = 0; $i < $j; ++$i) {
335
            if ($i != $j - 1) {
336
                $row[] = $comma[$i] . ',';
337
            } else {
338
                $row[] = $comma[$i];
339
            }
340
        }
341
        // ================= COMMA CICLE ================= //
342
        $ret .= implode("\n", $row);
343
        unset($j);
344
        $ret .= $this->getFootDatabaseTable();
345
346
        return $ret;
347
    }
348
349
    /**
350
     * @private function getDatabaseFields
351
     *
352
     * @param $moduleDirname
353
     * @return null|string
354
     */
355
    private function getTableRatings($moduleDirname)
356
    {
357
        $ret           = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $ret is dead and can be removed.
Loading history...
358
        $j             = 0;
359
        $comma         = [];
360
        $row           = [];
361
362
        $ret            = $this->getHeadDatabaseTable($moduleDirname, 'ratings', 6);
363
        $row[] = $this->getFieldRow('rate_id', 'INT(8)', 'UNSIGNED', 'NOT NULL', null, 'AUTO_INCREMENT');
364
        $comma[$j] = $this->getKey(2, 'rate_id');
365
        ++$j;
366
        $row[] = $this->getFieldRow('rate_itemid', 'INT(8)', null, 'NOT NULL', "DEFAULT '0'");
367
        $row[] = $this->getFieldRow('rate_source', 'INT(8)', null, 'NOT NULL', "DEFAULT '0'");
368
        $row[] = $this->getFieldRow('rate_value', 'INT(1)', null, 'NOT NULL', "DEFAULT '0'");
369
        $row[] = $this->getFieldRow('rate_uid', 'INT(8)', null, 'NOT NULL', "DEFAULT '0'");
370
        $row[] = $this->getFieldRow('rate_ip', 'VARCHAR(60)', null, 'NOT NULL', "DEFAULT ''");
371
        $row[] = $this->getFieldRow('rate_date', 'INT(8)', null, 'NOT NULL', "DEFAULT '0'");
372
373
374
        // ================= COMMA ================= //
375
        for ($i = 0; $i < $j; ++$i) {
376
            if ($i != $j - 1) {
377
                $row[] = $comma[$i] . ',';
378
            } else {
379
                $row[] = $comma[$i];
380
            }
381
        }
382
        // ================= COMMA CICLE ================= //
383
        $ret .= implode("\n", $row);
384
        unset($j);
385
        $ret .= $this->getFootDatabaseTable();
386
387
        return $ret;
388
    }
389
390
    /**
391
     * @private function getFootDatabaseTable
392
     *
393
     * @param null
394
     *
395
     * @return string
396
     */
397
    private function getFootDatabaseTable()
398
    {
399
        return "\n) ENGINE=InnoDB;\n\n";
400
    }
401
402
    /**
403
     * @private function getFieldRow
404
     *
405
     * @param $fieldName
406
     * @param $fieldTypeValue
407
     * @param $fieldAttribute
408
     * @param $fieldNull
409
     * @param $fieldDefault
410
     * @param $autoincrement
411
     *
412
     * @return string
413
     */
414
    private function getFieldRow($fieldName, $fieldTypeValue, $fieldAttribute = null, $fieldNull = null, $fieldDefault = null, $autoincrement = null)
415
    {
416
        $retAutoincrement  = "  `{$fieldName}` {$fieldTypeValue} {$fieldAttribute} {$fieldNull} {$autoincrement},";
417
        $retFieldAttribute = "  `{$fieldName}` {$fieldTypeValue} {$fieldAttribute} {$fieldNull} {$fieldDefault},";
418
        $fieldDefault      = "  `{$fieldName}` {$fieldTypeValue} {$fieldNull} {$fieldDefault},";
419
        $retShort          = "  `{$fieldName}` {$fieldTypeValue},";
420
421
        $ret = $retShort;
422
        if (null != $autoincrement) {
423
            $ret = $retAutoincrement;
424
        } elseif (null != $fieldAttribute) {
425
            $ret = $retFieldAttribute;
426
        } elseif (null === $fieldAttribute) {
427
            $ret = $fieldDefault;
428
        }
429
430
        return $ret;
431
    }
432
433
    /**
434
     * @private function getKey
435
     *
436
     * @param $key
437
     * @param $fieldName
438
     * @return string
439
     */
440
    private function getKey($key, $fieldName)
441
    {
442
        $ret = null;
443
        switch ($key) {
444
            case 2: // PRIMARY KEY
445
                $ret = "  PRIMARY KEY (`{$fieldName}`)";
446
                break;
447
            case 3: // UNIQUE KEY
448
                $ret = "  UNIQUE KEY `{$fieldName}` (`{$fieldName}`)";
449
                break;
450
            case 4: // KEY
451
                $ret = "  KEY `{$fieldName}` (`{$fieldName}`)";
452
                break;
453
            case 5: // INDEX
454
                $ret = "  INDEX (`{$fieldName}`)";
455
                break;
456
            case 6: // FULLTEXT KEY
457
                $ret = "  FULLTEXT KEY `{$fieldName}` (`{$fieldName}`)";
458
                break;
459
        }
460
461
        return $ret;
462
    }
463
464
    /**
465
     * @public function render
466
     *
467
     * @param null
468
     *
469
     * @return bool|string
470
     */
471
    public function render()
472
    {
473
        $module        = $this->getModule();
474
        $filename      = $this->getFileName();
475
        $moduleName    = mb_strtolower($module->getVar('mod_name'));
476
        $moduleDirname = mb_strtolower($module->getVar('mod_dirname'));
477
        $content       = $this->getHeaderSqlComments($moduleName);
478
        $content       .= $this->getDatabaseTables($module);
479
480
        $this->create($moduleDirname, 'sql', $filename, $content, _AM_MODULEBUILDER_FILE_CREATED, _AM_MODULEBUILDER_FILE_NOTCREATED);
481
482
        return $this->renderFile();
483
    }
484
}
485