loadTableFromArrayWithReplace()   B
last analyzed

Complexity

Conditions 6
Paths 11

Size

Total Lines 41
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 25
c 1
b 0
f 0
nc 11
nop 4
dl 0
loc 41
rs 8.8977
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\Newbb\{
21
    Common\Configurator,
22
    Helper,
23
    Utility
24
};
25
26
/** @var Helper $helper */
27
/** @var Utility $utility */
28
/** @var Configurator $configurator */
29
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
        if (Request::hasVar('ok', 'REQUEST') && 1 === Request::getInt('ok', 0)) {
60
            if (!$GLOBALS['xoopsSecurity']->check()) {
61
                redirect_header($helper->url('admin/index.php'), 3, implode(',', $GLOBALS['xoopsSecurity']->getErrors()));
62
            }
63
            clearSampleData();
64
        } else {
65
            xoops_cp_header();
66
            xoops_confirm(['ok' => 1, 'op' => 'clear'], 'index.php', sprintf(constant('CO_' . $moduleDirNameUpper . '_' . 'CLEAR_SAMPLEDATA')), constant('CO_' . $moduleDirNameUpper . '_' . 'CONFIRM'), true);
67
            xoops_cp_footer();
68
        }
69
        break;
70
}
71
72
// XMF TableLoad for SAMPLE data
73
74
/**
75
 * @return void
76
 */
77
function loadSampleData(): void
78
{
79
    global $xoopsConfig;
80
    $moduleDirName      = \basename(\dirname(__DIR__));
81
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
82
83
    $helper = Helper::getInstance();
84
    $utility      = new Utility();
85
    $configurator = new Configurator();
86
87
//    $tables = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getInfo('tables');
88
    $tables = $helper->getModule()
89
                     ->getInfo('tables');
90
91
    $language = 'english/';
92
    if (is_dir(__DIR__ . '/' . $xoopsConfig['language'])) {
93
        $language = $xoopsConfig['language'] . '/';
94
    }
95
96
    // load module tables
97
    foreach ($tables as $table) {
98
        $tabledata = Yaml::readWrapped($language . $table . '.yml');
99
        TableLoad::truncateTable($table);
100
        TableLoad::loadTableFromArray($table, $tabledata);
101
    }
102
103
    // load permissions
104
    $table     = 'group_permission';
105
    $tabledata = Yaml::readWrapped($language . $table . '.yml');
106
    $mid       = $helper->getModule()->getVar('mid');
107
    loadTableFromArrayWithReplace($table, $tabledata, 'gperm_modid', $mid);
108
109
    //  ---  COPY test folder files ---------------
110
    if (is_array($configurator->copyTestFolders) && count($configurator->copyTestFolders) > 0) {
111
        //        $file =  \dirname(__DIR__) . '/testdata/images/';
112
        foreach (array_keys($configurator->copyTestFolders) as $i) {
113
            $src  = $configurator->copyTestFolders[$i][0];
114
            $dest = $configurator->copyTestFolders[$i][1];
115
            $utility::rcopy($src, $dest);
116
        }
117
    }
118
    \redirect_header('../admin/index.php', 1, \constant('CO_' . $moduleDirNameUpper . '_' . 'LOAD_SAMPLEDATA_SUCCESS'));
119
}
120
121
/**
122
 * @return void
123
 */
124
function saveSampleData(): void
125
{
126
    $skipColumns = [];
127
    global $xoopsConfig;
128
    $moduleDirName      = \basename(\dirname(__DIR__));
129
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
130
    $helper             = Helper::getInstance();
131
    $tables             = $helper->getModule()->getInfo('tables');
132
133
    $languageFolder = __DIR__ . '/' . $xoopsConfig['language'];
134
    if (!file_exists($languageFolder . '/')) {
135
        Utility::createFolder($languageFolder . '/');
136
    }
137
    $exportFolder = $languageFolder . '/Exports-' . date('Y-m-d-H-i-s') . '/';
138
    Utility::createFolder($exportFolder);
139
140
    // save module tables
141
    foreach ($tables as $table) {
142
        TableLoad::saveTableToYamlFile($table, $exportFolder . $table . '.yml');
143
    }
144
145
    // save permissions
146
    $criteria = new \CriteriaCompo();
147
    $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

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