loadTableFromArrayWithReplace()   B
last analyzed

Complexity

Conditions 6
Paths 11

Size

Total Lines 41
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 6
eloc 25
c 2
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\Marquee\Common\Configurator;
21
use XoopsModules\Marquee\Helper;
22
use XoopsModules\Marquee\Utility;
23
24
/** @var Helper $helper */
25
/** @var Utility $utility */
26
/** @var Configurator $configurator */
27
require \dirname(__DIR__, 3) . '/include/cp_header.php';
28
require \dirname(__DIR__) . '/preloads/autoloader.php';
29
30
$op = Request::getCmd('op', '');
31
32
$moduleDirName      = \basename(\dirname(__DIR__));
33
$moduleDirNameUpper = \mb_strtoupper($moduleDirName);
34
35
$helper = Helper::getInstance();
36
// Load language files
37
$helper->loadLanguage('common');
38
39
switch ($op) {
40
    case 'load':
41
        if (Request::hasVar('ok', 'REQUEST') && 1 === Request::getInt('ok', 0)) {
42
            if (!$GLOBALS['xoopsSecurity']->check()) {
43
                redirect_header($helper->url('admin/index.php'), 3, implode(',', $GLOBALS['xoopsSecurity']->getErrors()));
44
            }
45
            loadSampleData();
46
        } else {
47
            xoops_cp_header();
48
            xoops_confirm(['ok' => 1, 'op' => 'load'], 'index.php', constant('CO_' . $moduleDirNameUpper . '_' . 'LOAD_SAMPLEDATA_CONFIRM'), constant('CO_' . $moduleDirNameUpper . '_' . 'CONFIRM'), true);
49
            xoops_cp_footer();
50
        }
51
        break;
52
    case 'save':
53
        saveSampleData();
54
        break;
55
    case 'clear':
56
        if (Request::hasVar('ok', 'REQUEST') && 1 === Request::getInt('ok', 0)) {
57
            if (!$GLOBALS['xoopsSecurity']->check()) {
58
                redirect_header($helper->url('admin/index.php'), 3, implode(',', $GLOBALS['xoopsSecurity']->getErrors()));
59
            }
60
            clearSampleData();
61
        } else {
62
            xoops_cp_header();
63
            xoops_confirm(['ok' => 1, 'op' => 'clear'], 'index.php', sprintf(constant('CO_' . $moduleDirNameUpper . '_' . 'CLEAR_SAMPLEDATA')), constant('CO_' . $moduleDirNameUpper . '_' . 'CONFIRM'), true);
64
            xoops_cp_footer();
65
        }
66
        break;
67
}
68
69
// XMF TableLoad for SAMPLE data
70
71
function loadSampleData(): void
72
{
73
    global $xoopsConfig;
74
    $moduleDirName      = \basename(\dirname(__DIR__));
75
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
76
77
    $utility      = new Utility();
78
    $configurator = new Configurator();
79
80
    $tables = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getInfo('tables');
81
82
    $language = 'english/';
83
    if (is_dir(__DIR__ . '/' . $xoopsConfig['language'])) {
84
        $language = $xoopsConfig['language'] . '/';
85
    }
86
87
    // load module tables
88
    foreach ($tables as $table) {
89
        $tabledata = Yaml::readWrapped($language . $table . '.yml');
90
        TableLoad::truncateTable($table);
91
        TableLoad::loadTableFromArray($table, $tabledata);
92
    }
93
94
    // load permissions
95
    $table     = 'group_permission';
96
    $tabledata = Yaml::readWrapped($language . $table . '.yml');
97
    $mid       = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getVar('mid');
98
    loadTableFromArrayWithReplace($table, $tabledata, 'gperm_modid', $mid);
99
100
    //  ---  COPY test folder files ---------------
101
    if ($configurator->copyTestFolders && \is_array($configurator->copyTestFolders)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $configurator->copyTestFolders of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
102
        //        $file =  \dirname(__DIR__) . '/testdata/images/';
103
        foreach (array_keys($configurator->copyTestFolders) as $i) {
104
            $src  = $configurator->copyTestFolders[$i][0];
105
            $dest = $configurator->copyTestFolders[$i][1];
106
            $utility::rcopy($src, $dest);
107
        }
108
    }
109
    \redirect_header('../admin/index.php', 1, \constant('CO_' . $moduleDirNameUpper . '_' . 'LOAD_SAMPLEDATA_SUCCESS'));
110
}
111
112
function saveSampleData(): void
113
{
114
    global $xoopsConfig;
115
    $moduleDirName      = \basename(\dirname(__DIR__));
116
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
117
    $helper             = Helper::getInstance();
118
    $tables             = $helper->getModule()->getInfo('tables');
119
120
    $languageFolder = __DIR__ . '/' . $xoopsConfig['language'];
121
    if (!file_exists($languageFolder . '/')) {
122
        Utility::createFolder($languageFolder . '/');
123
    }
124
    $exportFolder = $languageFolder . '/Exports-' . date('Y-m-d-H-i-s') . '/';
125
    Utility::createFolder($exportFolder);
126
127
    // save module tables
128
    foreach ($tables as $table) {
129
        TableLoad::saveTableToYamlFile($table, $exportFolder . $table . '.yml');
130
    }
131
132
    // save permissions
133
    $criteria = new \CriteriaCompo();
134
    $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

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