Completed
Push — master ( 2f6fab...c5b9c9 )
by Goffy
11s queued 10s
created

index.php ➔ loadTableFromArrayWithReplace()   B

Complexity

Conditions 6
Paths 11

Size

Total Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 11
nop 4
dl 0
loc 42
rs 8.6257
c 0
b 0
f 0
1
<?php
2
/**
3
 * You may not change or alter any portion of this comment or credits
4
 * of supporting developers from this source code or any supporting source code
5
 * which is considered copyrighted (c) material of the original comment or credit authors.
6
 * This program is distributed in the hope that it will be useful,
7
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
8
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
9
 *
10
 * @copyright       XOOPS Project (https://xoops.org)
11
 * @license         GNU GPL 2 (https://www.gnu.org/licenses/old-licenses/gpl-2.0.html)
12
 * @since           2.5.9
13
 * @author          Michael Beck (aka Mamba)
14
 */
15
16
use Xmf\Database\TableLoad;
17
use Xmf\Request;
18
use Xmf\Yaml;
19
use XoopsModules\Tools\{
20
    Helper,
21
    Common\Configurator,
22
    Utility
23
};
24
/** @var Helper $helper */
25
/** @var Utility $utility */
26
/** @var Configurator $configurator */
27
28
require dirname(__DIR__, 3) . '/include/cp_header.php';
29
require dirname(__DIR__) . '/preloads/autoloader.php';
30
31
$op = Request::getCmd('op', '');
32
33
$moduleDirName      = \basename(\dirname(__DIR__));
34
$moduleDirNameUpper = mb_strtoupper($moduleDirName);
35
36
$helper = Helper::getInstance();
37
// Load language files
38
$helper->loadLanguage('common');
39
40
switch ($op) {
41
    case 'load':
42
        if (Request::hasVar('ok', 'REQUEST') && 1 === Request::getInt('ok', 0)) {
43 View Code Duplication
            if (!$GLOBALS['xoopsSecurity']->check()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
44
                redirect_header($helper->url('admin/index.php'), 3, implode(',', $GLOBALS['xoopsSecurity']->getErrors()));
45
            }
46
            loadSampleData();
47
        } else {
48
            xoops_cp_header();
49
            xoops_confirm(['ok' => 1, 'op' => 'load'], 'index.php', sprintf(constant('CO_' . $moduleDirNameUpper . '_' . 'LOAD_SAMPLEDATA_CONFIRM')), constant('CO_' . $moduleDirNameUpper . '_' . 'CONFIRM'), true);
50
            xoops_cp_footer();
51
        }
52
        break;
53
    case 'save':
54
        saveSampleData();
55
        break;
56
    case 'clear':
57
        clearSampleData();
58
        break;
59
}
60
61
// XMF TableLoad for SAMPLE data
62
63
function loadSampleData()
64
{
65
    global $xoopsConfig;
66
    $moduleDirName      = \basename(\dirname(__DIR__));
67
    $moduleDirNameUpper = mb_strtoupper($moduleDirName);
68
69
    $utility      = new Utility();
70
    $configurator = new Configurator();
71
72
    $tables = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getInfo('tables');
73
74
    $language = 'english/';
75
    if (is_dir(__DIR__ . '/' . $xoopsConfig['language'])) {
76
        $language = $xoopsConfig['language'] . '/';
77
    }
78
79
    // load module tables
80
    foreach ($tables as $table) {
81
        $tabledata = Yaml::readWrapped($language . $table . '.yml');
82
        TableLoad::truncateTable($table);
83
        TableLoad::loadTableFromArray($table, $tabledata);
84
    }
85
86
    // load permissions
87
    $table     = 'group_permission';
88
    $tabledata = Yaml::readWrapped($language . $table . '.yml');
89
    $mid       = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getVar('mid');
90
    loadTableFromArrayWithReplace($table, $tabledata, 'gperm_modid', $mid);
91
92
    //  ---  COPY test folder files ---------------
93
    if (is_array($configurator->copyTestFolders) && count($configurator->copyTestFolders) > 0) {
94
        //        $file =  dirname(__DIR__) . '/testdata/images/';
95
        foreach (array_keys($configurator->copyTestFolders) as $i) {
96
            $src  = $configurator->copyTestFolders[$i][0];
97
            $dest = $configurator->copyTestFolders[$i][1];
98
            $utility::rcopy($src, $dest);
99
        }
100
    }
101
    \redirect_header('../admin/index.php', 1, \constant('CO_' . $moduleDirNameUpper . '_' . 'LOAD_SAMPLEDATA_SUCCESS'));
102
}
103
104
function saveSampleData()
105
{
106
    global $xoopsConfig;
107
    $moduleDirName      = \basename(\dirname(__DIR__));
108
    $moduleDirNameUpper = mb_strtoupper($moduleDirName);
109
    $helper             = Helper::getInstance();
110
    $tables             = $helper->getModule()->getInfo('tables');
111
112
    $languageFolder = __DIR__ . '/' . $xoopsConfig['language'];
113
    if (!file_exists($languageFolder . '/')) {
114
        Utility::createFolder($languageFolder . '/');
115
    }
116
    $exportFolder = $languageFolder . '/Exports-' . date('Y-m-d-H-i-s') . '/';
117
    Utility::createFolder($exportFolder);
118
119
    // save module tables
120
    foreach ($tables as $table) {
121
        TableLoad::saveTableToYamlFile($table, $exportFolder . $table . '.yml');
122
    }
123
124
    // save permissions
125
    $criteria = new \CriteriaCompo();
126
    $criteria->add(new \Criteria('gperm_modid', $helper->getModule()->getVar('mid')));
127
    $skipColumns[] = 'gperm_id';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$skipColumns was never initialized. Although not strictly required by PHP, it is generally a good practice to add $skipColumns = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
128
    TableLoad::saveTableToYamlFile('group_permission', $exportFolder . 'group_permission.yml', $criteria, $skipColumns);
129
    unset($criteria);
130
131
    \redirect_header('../admin/index.php', 1, \constant('CO_' . $moduleDirNameUpper . '_' . 'SAVE_SAMPLEDATA_SUCCESS'));
132
}
133
134
function exportSchema()
135
{
136
    $moduleDirName      = \basename(\dirname(__DIR__));
137
    $moduleDirNameUpper = mb_strtoupper($moduleDirName);
0 ignored issues
show
Unused Code introduced by
$moduleDirNameUpper is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
138
139
    try {
140
        // TODO set exportSchema
141
        //        $migrate = new Migrate($moduleDirName);
142
        //        $migrate->saveCurrentSchema();
143
        //
144
        //        redirect_header('../admin/index.php', 1, constant('CO_' . $moduleDirNameUpper . '_' . 'EXPORT_SCHEMA_SUCCESS'));
145
    } catch (\Throwable $e) {
0 ignored issues
show
Bug introduced by
The class Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
Unused Code introduced by
catch (\Throwable $e) { ...PORT_SCHEMA_ERROR')); } does not seem to be 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...
146
        exit(constant('CO_' . $moduleDirNameUpper . '_' . 'EXPORT_SCHEMA_ERROR'));
147
    }
148
}
149
150
/**
151
 * loadTableFromArrayWithReplace
152
 *
153
 * @param string $table  value with should be used insead of original value of $search
154
 *
155
 * @param array  $data   array of rows to insert
156
 *                       Each element of the outer array represents a single table row.
157
 *                       Each row is an associative array in 'column' => 'value' format.
158
 * @param string $search name of column for which the value should be replaced
159
 * @param        $replace
160
 * @return int number of rows inserted
161
 */
162
function loadTableFromArrayWithReplace($table, $data, $search, $replace)
163
{
164
    /** @var \XoopsMySQLDatabase $db */
165
    $db = \XoopsDatabaseFactory::getDatabaseConnection();
166
167
    $prefixedTable = $db->prefix($table);
168
    $count         = 0;
169
170
    $sql = 'DELETE FROM ' . $prefixedTable . ' WHERE `' . $search . '`=' . $db->quote($replace);
171
172
    $result = $db->queryF($sql);
0 ignored issues
show
Unused Code introduced by
$result is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
173
174
    foreach ($data as $row) {
175
        $insertInto  = 'INSERT INTO ' . $prefixedTable . ' (';
176
        $valueClause = ' VALUES (';
177
        $first       = true;
178
        foreach ($row as $column => $value) {
179
            if ($first) {
180
                $first = false;
181
            } else {
182
                $insertInto  .= ', ';
183
                $valueClause .= ', ';
184
            }
185
186
            $insertInto .= $column;
187
            if ($search === $column) {
188
                $valueClause .= $db->quote($replace);
189
            } else {
190
                $valueClause .= $db->quote($value);
191
            }
192
        }
193
194
        $sql = $insertInto . ') ' . $valueClause . ')';
195
196
        $result = $db->queryF($sql);
197
        if (false !== $result) {
198
            ++$count;
199
        }
200
    }
201
202
    return $count;
203
}
204
205
function clearSampleData(){
206
    $moduleDirName      = \basename(\dirname(__DIR__));
207
    $moduleDirNameUpper = mb_strtoupper($moduleDirName);
208
    $helper             = Helper::getInstance();
209
    // Load language files
210
    $helper->loadLanguage('common');
211
    $tables = $helper->getModule()->getInfo('tables');
212
    // truncate module tables
213
    foreach ($tables as $table) {
214
        \Xmf\Database\TableLoad::truncateTable($table);
215
    }
216
    redirect_header($helper->url('admin/index.php'), 1, constant('CO_' . $moduleDirNameUpper . '_' . 'CLEAR_SAMPLEDATA_OK'));
217
}
218