loadSampleData()   B
last analyzed

Complexity

Conditions 6
Paths 8

Size

Total Lines 39
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

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

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