clearSampleData()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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

153
            'gperm_modid', /** @scrutinizer ignore-type */ $helper->getModule()
Loading history...
154
                                  ->getVar('mid')
155
        )
156
    );
157
    $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...
158
    TableLoad::saveTableToYamlFile('group_permission', $exportFolder . 'group_permission.yml', $criteria, $skipColumns);
159
    unset($criteria);
160
161
    \redirect_header('../admin/index.php', 1, \constant('CO_' . $moduleDirNameUpper . '_' . 'SAVE_SAMPLEDATA_SUCCESS'));
162
}
163
164
/**
165
 * @return void
166
 */
167
function exportSchema()
168
{
169
    $moduleDirName      = \basename(\dirname(__DIR__));
170
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
0 ignored issues
show
Unused Code introduced by
The assignment to $moduleDirNameUpper is dead and can be removed.
Loading history...
171
172
    try {
173
        // TODO set exportSchema
174
        //        $migrate = new Migrate($moduleDirName);
175
        //        $migrate->saveCurrentSchema();
176
        //
177
        //        redirect_header('../admin/index.php', 1, constant('CO_' . $moduleDirNameUpper . '_' . 'EXPORT_SCHEMA_SUCCESS'));
178
    } 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...
179
        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...
180
    }
181
}
182
183
/**
184
 * loadTableFromArrayWithReplace
185
 *
186
 * @param string $table  value with should be used insead of original value of $search
187
 *
188
 * @param array  $data   array of rows to insert
189
 *                       Each element of the outer array represents a single table row.
190
 *                       Each row is an associative array in 'column' => 'value' format.
191
 * @param string $search name of column for which the value should be replaced
192
 * @param        $replace
193
 * @return int number of rows inserted
194
 */
195
function loadTableFromArrayWithReplace($table, $data, $search, $replace)
196
{
197
    /** @var \XoopsMySQLDatabase $db */
198
    $db = \XoopsDatabaseFactory::getDatabaseConnection();
199
200
    $prefixedTable = $db->prefix($table);
201
    $count         = 0;
202
203
    $sql = 'DELETE FROM ' . $prefixedTable . ' WHERE `' . $search . '`=' . $db->quote($replace);
204
205
    $result = $db->queryF($sql);
206
207
    if ($result) {
208
        foreach ($data as $row) {
209
            $insertInto  = 'INSERT INTO ' . $prefixedTable . ' (';
210
            $valueClause = ' VALUES (';
211
            $first       = true;
212
            foreach ($row as $column => $value) {
213
                if ($first) {
214
                    $first = false;
215
                } else {
216
                    $insertInto  .= ', ';
217
                    $valueClause .= ', ';
218
                }
219
220
                $insertInto .= $column;
221
                if ($search === $column) {
222
                    $valueClause .= $db->quote($replace);
223
                } else {
224
                    $valueClause .= $db->quote($value);
225
                }
226
            }
227
228
            $sql = $insertInto . ') ' . $valueClause . ')';
229
230
            $result = $db->queryF($sql);
231
            if (false !== $result) {
232
                ++$count;
233
            }
234
        }
235
    }
236
    return $count;
237
}
238
239
/**
240
 * @return void
241
 */
242
function clearSampleData()
243
{
244
    $moduleDirName      = \basename(\dirname(__DIR__));
245
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
246
    $helper             = Helper::getInstance();
247
    // Load language files
248
    $helper->loadLanguage('common');
249
    $tables = $helper->getModule()
250
                     ->getInfo('tables');
251
    // truncate module tables
252
    foreach ($tables as $table) {
253
        \Xmf\Database\TableLoad::truncateTable($table);
254
    }
255
    redirect_header($helper->url('admin/index.php'), 1, constant('CO_' . $moduleDirNameUpper . '_' . 'CLEAR_SAMPLEDATA_OK'));
256
}
257