clearSampleData()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 9
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 14
rs 9.9666
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\Xoopsfaq\{
21
    Common\Configurator,
22
    Helper,
23
    Utility
24
};
25
26
/** @var Helper $helper */
27
/** @var Utility $utility */
28
/** @var Configurator $configurator */
29
require \dirname(__DIR__, 3) . '/include/cp_header.php';
30
require \dirname(__DIR__) . '/preloads/autoloader.php';
31
32
$op = Request::getCmd('op', '');
33
34
$moduleDirName      = \basename(\dirname(__DIR__));
35
$moduleDirNameUpper = \mb_strtoupper($moduleDirName);
36
37
$helper = Helper::getInstance();
38
// Load language files
39
$helper->loadLanguage('common');
40
41
switch ($op) {
42
    case 'load':
43
        if (Request::hasVar('ok', 'REQUEST') && 1 === Request::getInt('ok', 0)) {
44
            if (!$GLOBALS['xoopsSecurity']->check()) {
45
                redirect_header($helper->url('admin/index.php'), 3, implode(',', $GLOBALS['xoopsSecurity']->getErrors()));
46
            }
47
            loadSampleData();
48
        } else {
49
            xoops_cp_header();
50
            xoops_confirm(['ok' => 1, 'op' => 'load'], 'index.php', constant('CO_' . $moduleDirNameUpper . '_' . 'LOAD_SAMPLEDATA_CONFIRM'), constant('CO_' . $moduleDirNameUpper . '_' . 'CONFIRM'), true);
51
            xoops_cp_footer();
52
        }
53
        break;
54
    case 'save':
55
        saveSampleData();
56
        break;
57
    case 'clear':
58
        if (Request::hasVar('ok', 'REQUEST') && 1 === Request::getInt('ok', 0)) {
59
            if (!$GLOBALS['xoopsSecurity']->check()) {
60
                redirect_header($helper->url('admin/index.php'), 3, implode(',', $GLOBALS['xoopsSecurity']->getErrors()));
61
            }
62
            clearSampleData();
63
        } else {
64
            xoops_cp_header();
65
            xoops_confirm(['ok' => 1, 'op' => 'clear'], 'index.php', sprintf(constant('CO_' . $moduleDirNameUpper . '_' . 'CLEAR_SAMPLEDATA')), constant('CO_' . $moduleDirNameUpper . '_' . 'CONFIRM'), true);
66
            xoops_cp_footer();
67
        }
68
        break;
69
}
70
71
// XMF TableLoad for SAMPLE data
72
73
function loadSampleData(): void
74
{
75
    global $xoopsConfig;
76
    $moduleDirName      = \basename(\dirname(__DIR__));
77
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
78
79
    $utility      = new Utility();
80
    $configurator = new Configurator();
81
82
    $tables = \Xmf\Module\Helper::getHelper($moduleDirName)
83
                                ->getModule()
84
                                ->getInfo('tables');
85
86
    $language = 'english/';
87
    if (is_dir(__DIR__ . '/' . $xoopsConfig['language'])) {
88
        $language = $xoopsConfig['language'] . '/';
89
    }
90
91
    // load module tables
92
    foreach ($tables as $table) {
93
        $tabledata = Yaml::readWrapped($language . $table . '.yml');
94
        TableLoad::truncateTable($table);
95
        TableLoad::loadTableFromArray($table, $tabledata);
96
    }
97
98
    // load permissions
99
    $table     = 'group_permission';
100
    $tabledata = Yaml::readWrapped($language . $table . '.yml');
101
    $mid       = \Xmf\Module\Helper::getHelper($moduleDirName)
102
                                   ->getModule()
103
                                   ->getVar('mid');
104
    loadTableFromArrayWithReplace($table, $tabledata, 'gperm_modid', $mid);
105
106
    //  ---  COPY test folder files ---------------
107
    if (is_array($configurator->copyTestFolders) && count($configurator->copyTestFolders) > 0) {
108
        //        $file =  \dirname(__DIR__) . '/testdata/images/';
109
        foreach (array_keys($configurator->copyTestFolders) as $i) {
110
            $src  = $configurator->copyTestFolders[$i][0];
111
            $dest = $configurator->copyTestFolders[$i][1];
112
            $utility->rcopy($src, $dest);
113
        }
114
    }
115
    \redirect_header('../admin/index.php', 1, \constant('CO_' . $moduleDirNameUpper . '_' . 'LOAD_SAMPLEDATA_SUCCESS'));
116
}
117
118
function saveSampleData(): void
119
{
120
    $skipColumns = [];
121
    global $xoopsConfig;
122
    $moduleDirName      = \basename(\dirname(__DIR__));
123
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
124
    $helper             = Helper::getInstance();
125
    $tables             = $helper->getModule()
126
                                 ->getInfo('tables');
127
128
    $languageFolder = __DIR__ . '/' . $xoopsConfig['language'];
129
    if (!file_exists($languageFolder . '/')) {
130
        Utility::createFolder($languageFolder . '/');
131
    }
132
    $exportFolder = $languageFolder . '/Exports-' . date('Y-m-d-H-i-s') . '/';
133
    Utility::createFolder($exportFolder);
134
135
    // save module tables
136
    foreach ($tables as $table) {
137
        TableLoad::saveTableToYamlFile($table, $exportFolder . $table . '.yml');
138
    }
139
140
    // save permissions
141
    $criteria = new \CriteriaCompo();
142
    $criteria->add(
143
        new \Criteria(
144
            'gperm_modid', (string)$helper->getModule()
145
                                          ->getVar('mid')
146
        )
147
    );
148
    $skipColumns[] = 'gperm_id';
149
    TableLoad::saveTableToYamlFile('group_permission', $exportFolder . 'group_permission.yml', $criteria, $skipColumns);
150
    unset($criteria);
151
152
    \redirect_header('../admin/index.php', 1, \constant('CO_' . $moduleDirNameUpper . '_' . 'SAVE_SAMPLEDATA_SUCCESS'));
153
}
154
155
function exportSchema(): void
156
{
157
    $moduleDirName      = \basename(\dirname(__DIR__));
158
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
0 ignored issues
show
Unused Code introduced by
The assignment to $moduleDirNameUpper is dead and can be removed.
Loading history...
159
160
    try {
161
        // TODO set exportSchema
162
        //        $migrate = new Migrate($moduleDirName);
163
        //        $migrate->saveCurrentSchema();
164
        //
165
        //        redirect_header('../admin/index.php', 1, constant('CO_' . $moduleDirNameUpper . '_' . 'EXPORT_SCHEMA_SUCCESS'));
166
    } 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...
167
        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...
168
    }
169
}
170
171
/**
172
 * loadTableFromArrayWithReplace
173
 *
174
 * @param string $table  value which should be used instead of original value of $search
175
 *
176
 * @param array  $data   array of rows to insert
177
 *                       Each element of the outer array represents a single table row.
178
 *                       Each row is an associative array in 'column' => 'value' format.
179
 * @param string $search name of column for which the value should be replaced
180
 * @return int number of rows inserted
181
 */
182
function loadTableFromArrayWithReplace(string $table, array $data, string $search, int $replace): int
183
{
184
    /** @var \XoopsMySQLDatabase $db */
185
    $db = \XoopsDatabaseFactory::getDatabaseConnection();
186
187
    $prefixedTable = $db->prefix($table);
188
    $count         = 0;
189
190
    $sql = 'DELETE FROM ' . $prefixedTable . ' WHERE `' . $search . '`=' . $db->quote((string)$replace);
191
192
    $result = $db->queryF($sql);
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
193
194
    foreach ($data as $row) {
195
        $insertInto  = 'INSERT INTO ' . $prefixedTable . ' (';
196
        $valueClause = ' VALUES (';
197
        $first       = true;
198
        foreach ($row as $column => $value) {
199
            if ($first) {
200
                $first = false;
201
            } else {
202
                $insertInto  .= ', ';
203
                $valueClause .= ', ';
204
            }
205
206
            $insertInto .= $column;
207
            if ($search === $column) {
208
                $valueClause .= $db->quote((string)$replace);
209
            } else {
210
                $valueClause .= $db->quote((string)$value);
211
            }
212
        }
213
214
        $sql = $insertInto . ') ' . $valueClause . ')';
215
216
        $result = $db->queryF($sql);
217
        if (false !== $result) {
218
            ++$count;
219
        }
220
    }
221
222
    return $count;
223
}
224
225
function clearSampleData(): void
226
{
227
    $moduleDirName      = \basename(\dirname(__DIR__));
228
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
229
    $helper             = Helper::getInstance();
230
    // Load language files
231
    $helper->loadLanguage('common');
232
    $tables = $helper->getModule()
233
                     ->getInfo('tables');
234
    // truncate module tables
235
    foreach ($tables as $table) {
236
        \Xmf\Database\TableLoad::truncateTable($table);
237
    }
238
    redirect_header($helper->url('admin/index.php'), 1, constant('CO_' . $moduleDirNameUpper . '_' . 'CLEAR_SAMPLEDATA_OK'));
239
}
240