Passed
Pull Request — master (#11)
by Michael
11:08
created

clearSampleData()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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

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