Passed
Branch master (11f048)
by Michael
13:33
created

deleteRecords()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 4
eloc 9
c 1
b 0
f 1
nc 4
nop 2
dl 0
loc 15
rs 9.9666
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
 * @since           2.5.9
16
 * @author          Michael Beck (aka Mamba): https://github.com/mambax7
17
 */
18
19
use Xmf\Database\TableLoad;
20
use Xmf\Database\Tables;
21
use Xmf\Request;
22
use Xmf\Yaml;
23
use XoopsModules\Publisher\Common\Configurator;
24
use XoopsModules\Publisher\Helper;
25
use XoopsModules\Publisher\Utility;
26
27
/** @var Helper $helper */
28
/** @var Utility $utility */
29
/** @var Configurator $configurator */
30
require \dirname(__DIR__, 3) . '/include/cp_header.php';
31
require \dirname(__DIR__) . '/preloads/autoloader.php';
32
33
$op = Request::getCmd('op', '');
34
35
$moduleDirName      = \basename(\dirname(__DIR__));
36
$moduleDirNameUpper = \mb_strtoupper($moduleDirName);
37
38
$helper = Helper::getInstance();
39
// Load language files
40
$helper->loadLanguage('common');
41
42
switch ($op) {
43
    case 'load':
44
        if (Request::hasVar('ok', 'REQUEST') && 1 === Request::getInt('ok', 0)) {
45
            if (!$GLOBALS['xoopsSecurity']->check()) {
46
                redirect_header($helper->url('admin/index.php'), 3, implode(',', $GLOBALS['xoopsSecurity']->getErrors()));
47
            }
48
            loadSampleData();
49
        } else {
50
            xoops_cp_header();
51
            xoops_confirm(['ok' => 1, 'op' => 'load'], 'index.php', constant('CO_' . $moduleDirNameUpper . '_' . 'LOAD_SAMPLEDATA_CONFIRM'), constant('CO_' . $moduleDirNameUpper . '_' . 'CONFIRM'), true);
52
            xoops_cp_footer();
53
        }
54
        break;
55
    case 'save':
56
        saveSampleData();
57
        break;
58
    case 'clear':
59
        clearSampleData();
60
        break;
61
}
62
63
// XMF TableLoad for SAMPLE data
64
65
function loadSampleData(): void
66
{
67
    global $xoopsConfig;
68
    $moduleDirName      = \basename(\dirname(__DIR__));
69
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
70
71
    $utility      = new Utility();
72
    $configurator = new Configurator();
73
74
    $tables = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getInfo('tables');
75
76
    $language = 'english/';
77
    if (is_dir(__DIR__ . '/' . $xoopsConfig['language'])) {
78
        $language = $xoopsConfig['language'] . '/';
79
    }
80
81
    clearImages();
82
    // load module tables
83
    foreach ($tables as $table) {
84
        $tabledata = Yaml::readWrapped($language . $table . '.yml');
85
        TableLoad::truncateTable($table);
86
        TableLoad::loadTableFromArray($table, $tabledata);
87
    }
88
89
    // load permissions
90
    $table     = 'group_permission';
91
    $tabledata = Yaml::readWrapped($language . $table . '.yml');
92
    $mid       = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getVar('mid');
93
    loadTableFromArrayWithReplace($table, $tabledata, 'gperm_modid', $mid);
94
95
    if (1 === $configurator->testimages['images']) {
96
        // load test image categories
97
        $table     = 'imagecategory';
98
        $tabledata = Yaml::readWrapped($language . $table . '.yml');
99
        $mid       = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getVar('mid');
100
        loadTableFromArrayWithReplace($table, $tabledata, 'gperm_modid', $mid);
101
102
        // load test images
103
        $table     = 'image';
104
        $tabledata = Yaml::readWrapped($language . $table . '.yml');
105
        $mid       = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getVar('mid');
106
        loadTableFromArrayWithReplace($table, $tabledata, 'gperm_modid', $mid);
107
    }
108
109
110
    //  ---  COPY test folder files ---------------
111
    if (is_array($configurator->copyTestFolders) && count($configurator->copyTestFolders) > 0) {
112
        //        $file =  \dirname(__DIR__) . '/testdata/images/';
113
        foreach (array_keys($configurator->copyTestFolders) as $i) {
114
            $src  = $configurator->copyTestFolders[$i][0];
115
            $dest = $configurator->copyTestFolders[$i][1];
116
            $utility::rcopy($src, $dest);
117
        }
118
    }
119
    \redirect_header('../admin/index.php', 1, \constant('CO_' . $moduleDirNameUpper . '_' . 'LOAD_SAMPLEDATA_SUCCESS'));
120
}
121
122
function saveSampleData(): void
123
{
124
    global $xoopsConfig;
125
    $moduleDirName      = \basename(\dirname(__DIR__));
126
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
127
    $helper             = Helper::getInstance();
128
    $tables             = $helper->getModule()->getInfo('tables');
129
    $configurator = new Configurator();
130
131
    $languageFolder = __DIR__ . '/' . $xoopsConfig['language'];
132
    if (!file_exists($languageFolder . '/')) {
133
        Utility::createFolder($languageFolder . '/');
134
    }
135
    $exportFolder = $languageFolder . '/Exports-' . date('Y-m-d-H-i-s') . '/';
136
    Utility::createFolder($exportFolder);
137
138
    // save module tables
139
    foreach ($tables as $table) {
140
        TableLoad::saveTableToYamlFile($table, $exportFolder . $table . '.yml');
141
    }
142
143
    // save permissions
144
    $criteria = new \CriteriaCompo();
145
    $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

145
    $criteria->add(new \Criteria('gperm_modid', /** @scrutinizer ignore-type */ $helper->getModule()->getVar('mid')));
Loading history...
146
    $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...
147
    TableLoad::saveTableToYamlFile('group_permission', $exportFolder . 'group_permission.yml', $criteria, $skipColumns);
148
    unset($criteria);
149
150
    // save test image category
151
    if (1 === $configurator->testimages['images']) {
152
        $criteria = new \CriteriaCompo();
153
        $criteria->add(new \Criteria('imgcat_name', $configurator->testimages['imgcat_name']));
154
        TableLoad::saveTableToYamlFile('imagecategory', $exportFolder . 'imagecategory.yml', $criteria);
155
        unset($criteria);
156
157
        // save test images
158
        $criteria = new \CriteriaCompo();
159
        $criteria->add(new \Criteria('imgcat_id', $configurator->testimages['imgcat_id']));
160
        TableLoad::saveTableToYamlFile('image', $exportFolder . 'image.yml', $criteria);
161
        unset($criteria);
162
    }
163
164
    \redirect_header('../admin/index.php', 1, \constant('CO_' . $moduleDirNameUpper . '_' . 'SAVE_SAMPLEDATA_SUCCESS'));
165
}
166
167
function exportSchema(): void
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);
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
206
207
    foreach ($data as $row) {
208
        $insertInto  = 'INSERT INTO ' . $prefixedTable . ' (';
209
        $valueClause = ' VALUES (';
210
        $first       = true;
211
        foreach ($row as $column => $value) {
212
            if ($first) {
213
                $first = false;
214
            } else {
215
                $insertInto  .= ', ';
216
                $valueClause .= ', ';
217
            }
218
219
            $insertInto .= $column;
220
            if ($search === $column) {
221
                $valueClause .= $db->quote($replace);
222
            } else {
223
                $valueClause .= $db->quote($value);
224
            }
225
        }
226
227
        $sql = $insertInto . ') ' . $valueClause . ')';
228
229
        $result = $db->queryF($sql);
230
        if (false !== $result) {
231
            ++$count;
232
        }
233
    }
234
235
    return $count;
236
}
237
238
function clearSampleData(): void
239
{
240
    $moduleDirName      = \basename(\dirname(__DIR__));
241
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
242
    $helper             = Helper::getInstance();
243
    // Load language files
244
    $helper->loadLanguage('common');
245
    $tables = $helper->getModule()->getInfo('tables');
246
    // truncate module tables
247
    foreach ($tables as $table) {
248
        \Xmf\Database\TableLoad::truncateTable($table);
249
    }
250
251
    clearImages();
252
253
    redirect_header($helper->url('admin/index.php'), 1, constant('CO_' . $moduleDirNameUpper . '_' . 'CLEAR_SAMPLEDATA_OK'));
254
}
255
256
function clearImages(): void
257
{
258
    $configurator = new Configurator();
259
    // clear test images & image category
260
    if (1 === $configurator->testimages['images']) {
261
        // clear test image category
262
        $criteria = new \CriteriaCompo();
263
        $criteria->add(new \Criteria('imgcat_name', $configurator->testimages['imgcat_name']));
264
        deleteRecords($criteria, 'imagecategory');//::saveTableToYamlFile('imagecategory', $exportFolder . 'imagecategory.yml', $criteria);
265
        unset($criteria);
266
267
        // clear test images
268
        $criteria = new \CriteriaCompo();
269
        $criteria->add(new \Criteria('imgcat_id', $configurator->testimages['imgcat_id']));
270
        deleteRecords($criteria, 'image');
271
        unset($criteria);
272
    }
273
}
274
275
function deleteRecords(\CriteriaCompo $criteria = null, string $table): bool
276
{
277
    /** @var \XoopsMySQLDatabase $db */
278
    $db = \XoopsDatabaseFactory::getDatabaseConnection();
279
    $prefixedTable = $db->prefix($table);
280
    $sql = 'DELETE FROM ' . $prefixedTable . ' ';
281
    if (isset($criteria) && is_subclass_of($criteria, '\CriteriaElement')) {
282
        /* @var  \CriteriaCompo $criteria */
283
        $sql .= $criteria->renderWhere();
284
    }
285
    $result = $db->queryF($sql);
286
    if ($result) {
287
        return true;
288
    }
289
    return false;
290
}
291