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

loadTableFromArrayWithReplace()   B

Complexity

Conditions 7
Paths 2

Size

Total Lines 42
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

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

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