exportSchema()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 13
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 5
c 2
b 0
f 0
dl 0
loc 13
rs 10
cc 2
nc 1
nop 0
1
<?php declare(strict_types=1);
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
 * This program is distributed in the hope that it will be useful,
8
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10
 *
11
 * @copyright       XOOPS Project (https://xoops.org)
12
 * @license         GNU GPL 2 (https://www.gnu.org/licenses/old-licenses/gpl-2.0.html)
13
 * @since           2.5.9
14
 * @author          Michael Beck (aka Mamba)
15
 */
16
17
use Xmf\Database\TableLoad;
18
use Xmf\Request;
19
use Xmf\Yaml;
20
use XoopsModules\Smartfaq\{
21
    Helper,
22
    Common\Configurator,
23
    Utility
24
};
25
26
require \dirname(__DIR__, 3) . '/include/cp_header.php';
27
require \dirname(__DIR__) . '/preloads/autoloader.php';
28
29
$op = Request::getCmd('op', '');
30
31
$moduleDirName      = \basename(\dirname(__DIR__));
32
$moduleDirNameUpper = \mb_strtoupper($moduleDirName);
33
34
$helper = Helper::getInstance();
35
// Load language files
36
$helper->loadLanguage('common');
37
38
switch ($op) {
39
    case 'load':
40
        if (Request::hasVar('ok', 'REQUEST') && 1 === Request::getInt('ok', 0)) {
41
            if (!$GLOBALS['xoopsSecurity']->check()) {
42
                redirect_header($helper->url('admin/index.php'), 3, implode(',', $GLOBALS['xoopsSecurity']->getErrors()));
43
            }
44
            loadSampleData();
45
        } else {
46
            xoops_cp_header();
47
            xoops_confirm(['ok' => 1, 'op' => 'load'], 'index.php', constant('CO_' . $moduleDirNameUpper . '_' . 'LOAD_SAMPLEDATA_CONFIRM'), constant('CO_' . $moduleDirNameUpper . '_' . 'CONFIRM'), true);
48
            xoops_cp_footer();
49
        }
50
        break;
51
    case 'save':
52
        saveSampleData();
53
        break;
54
    case 'clear':
55
        if (Request::hasVar('ok', 'REQUEST') && 1 === Request::getInt('ok', 0)) {
56
            if (!$GLOBALS['xoopsSecurity']->check()) {
57
                redirect_header($helper->url('admin/index.php'), 3, implode(',', $GLOBALS['xoopsSecurity']->getErrors()));
58
            }
59
            clearSampleData();
60
        } else {
61
            xoops_cp_header();
62
            xoops_confirm(['ok' => 1, 'op' => 'clear'], 'index.php', sprintf(constant('CO_' . $moduleDirNameUpper . '_' . 'CLEAR_SAMPLEDATA')), constant('CO_' . $moduleDirNameUpper . '_' . 'CONFIRM'), true);
63
            xoops_cp_footer();
64
        }
65
        break;
66
}
67
68
// XMF TableLoad for SAMPLE data
69
70
function loadSampleData(): void
71
{
72
    global $xoopsConfig;
73
    $moduleDirName      = \basename(\dirname(__DIR__));
74
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
75
76
    $utility      = new Utility();
77
    $configurator = new Configurator();
78
79
    $tables = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getInfo('tables');
80
81
    $language = 'english/';
82
    if (is_dir(__DIR__ . '/' . $xoopsConfig['language'])) {
83
        $language = $xoopsConfig['language'] . '/';
84
    }
85
86
    // load module tables
87
    foreach ($tables as $table) {
88
        $tabledata = Yaml::readWrapped($language . $table . '.yml');
89
        TableLoad::truncateTable($table);
90
        TableLoad::loadTableFromArray($table, $tabledata);
91
    }
92
93
    // load permissions
94
    $table     = 'group_permission';
95
    $tabledata = Yaml::readWrapped($language . $table . '.yml');
96
    $mid       = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getVar('mid');
97
    loadTableFromArrayWithReplace($table, $tabledata, 'gperm_modid', $mid);
98
99
    //  ---  COPY test folder files ---------------
100
    if (is_array($configurator->copyTestFolders) && count($configurator->copyTestFolders) > 0) {
101
        //        $file =  \dirname(__DIR__) . '/testdata/images/';
102
        foreach (array_keys($configurator->copyTestFolders) as $i) {
103
            $src  = $configurator->copyTestFolders[$i][0];
104
            $dest = $configurator->copyTestFolders[$i][1];
105
            $utility::rcopy($src, $dest);
106
        }
107
    }
108
    \redirect_header('../admin/index.php', 1, \constant('CO_' . $moduleDirNameUpper . '_' . 'LOAD_SAMPLEDATA_SUCCESS'));
109
}
110
111
function saveSampleData(): void
112
{
113
    global $xoopsConfig;
114
    $moduleDirName      = \basename(\dirname(__DIR__));
115
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
116
    $helper             = Helper::getInstance();
117
    $tables             = $helper->getModule()->getInfo('tables');
118
119
    $languageFolder = __DIR__ . '/' . $xoopsConfig['language'];
120
    if (!file_exists($languageFolder . '/')) {
121
        Utility::createFolder($languageFolder . '/');
122
    }
123
    $exportFolder = $languageFolder . '/Exports-' . date('Y-m-d-H-i-s') . '/';
124
    Utility::createFolder($exportFolder);
125
126
    // save module tables
127
    foreach ($tables as $table) {
128
        TableLoad::saveTableToYamlFile($table, $exportFolder . $table . '.yml');
129
    }
130
131
    // save permissions
132
    $criteria = new \CriteriaCompo();
133
    $criteria->add(new \Criteria('gperm_modid', $helper->getModule()->getVar('mid')));
0 ignored issues
show
Bug introduced by
It seems like $helper->getModule()->getVar('mid') can also be of type array and array; however, parameter $value of Criteria::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

133
    $criteria->add(new \Criteria('gperm_modid', /** @scrutinizer ignore-type */ $helper->getModule()->getVar('mid')));
Loading history...
134
    $skipColumns[] = 'gperm_id';
0 ignored issues
show
Comprehensibility Best Practice introduced by
$skipColumns was never initialized. Although not strictly required by PHP, it is generally a good practice to add $skipColumns = array(); before regardless.
Loading history...
135
    TableLoad::saveTableToYamlFile('group_permission', $exportFolder . 'group_permission.yml', $criteria, $skipColumns);
136
    unset($criteria);
137
138
    \redirect_header('../admin/index.php', 1, \constant('CO_' . $moduleDirNameUpper . '_' . 'SAVE_SAMPLEDATA_SUCCESS'));
139
}
140
141
function exportSchema(): void
142
{
143
    $moduleDirName      = \basename(\dirname(__DIR__));
144
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
0 ignored issues
show
Unused Code introduced by
The assignment to $moduleDirNameUpper is dead and can be removed.
Loading history...
145
146
    try {
147
        // TODO set exportSchema
148
        //        $migrate = new Migrate($moduleDirName);
149
        //        $migrate->saveCurrentSchema();
150
        //
151
        //        redirect_header('../admin/index.php', 1, constant('CO_' . $moduleDirNameUpper . '_' . 'EXPORT_SCHEMA_SUCCESS'));
152
    } catch (\Throwable $e) {
0 ignored issues
show
Unused Code introduced by
catch (\Throwable $e) is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
153
        exit(constant('CO_' . $moduleDirNameUpper . '_' . 'EXPORT_SCHEMA_ERROR'));
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
154
    }
155
}
156
157
/**
158
 * loadTableFromArrayWithReplace
159
 *
160
 * @param string $table  value with should be used insead of original value of $search
161
 *
162
 * @param array  $data   array of rows to insert
163
 *                       Each element of the outer array represents a single table row.
164
 *                       Each row is an associative array in 'column' => 'value' format.
165
 * @param string $search name of column for which the value should be replaced
166
 * @param        $replace
167
 * @return int number of rows inserted
168
 */
169
function loadTableFromArrayWithReplace($table, $data, $search, $replace)
170
{
171
    /** @var \XoopsMySQLDatabase $db */
172
    $db = \XoopsDatabaseFactory::getDatabaseConnection();
173
174
    $prefixedTable = $db->prefix($table);
175
    $count         = 0;
176
177
    $sql = 'DELETE FROM ' . $prefixedTable . ' WHERE `' . $search . '`=' . $db->quote($replace);
178
179
    $result = $db->queryF($sql);
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
180
181
    foreach ($data as $row) {
182
        $insertInto  = 'INSERT INTO ' . $prefixedTable . ' (';
183
        $valueClause = ' VALUES (';
184
        $first       = true;
185
        foreach ($row as $column => $value) {
186
            if ($first) {
187
                $first = false;
188
            } else {
189
                $insertInto  .= ', ';
190
                $valueClause .= ', ';
191
            }
192
193
            $insertInto .= $column;
194
            if ($search === $column) {
195
                $valueClause .= $db->quote($replace);
196
            } else {
197
                $valueClause .= $db->quote($value);
198
            }
199
        }
200
201
        $sql = $insertInto . ') ' . $valueClause . ')';
202
203
        $result = $db->queryF($sql);
204
        if (false !== $result) {
205
            ++$count;
206
        }
207
    }
208
209
    return $count;
210
}
211
212
function clearSampleData(): void
213
{
214
    $moduleDirName      = \basename(\dirname(__DIR__));
215
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
216
    $helper             = Helper::getInstance();
217
    // Load language files
218
    $helper->loadLanguage('common');
219
    $tables = $helper->getModule()->getInfo('tables');
220
    // truncate module tables
221
    foreach ($tables as $table) {
222
        \Xmf\Database\TableLoad::truncateTable($table);
223
    }
224
    redirect_header($helper->url('admin/index.php'), 1, constant('CO_' . $moduleDirNameUpper . '_' . 'CLEAR_SAMPLEDATA_OK'));
225
}
226