loadSampleData()   B
last analyzed

Complexity

Conditions 6
Paths 8

Size

Total Lines 39
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 23
nc 8
nop 0
dl 0
loc 39
rs 8.9297
c 0
b 0
f 0
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\Countdown\{
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
        clearSampleData();
62
        break;
63
}
64
65
// XMF TableLoad for SAMPLE data
66
67
function loadSampleData()
68
{
69
    global $xoopsConfig;
70
    $moduleDirName      = \basename(\dirname(__DIR__));
71
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
72
73
    $utility      = new Utility();
74
    $configurator = new Configurator();
75
76
    $tables = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getInfo('tables');
77
78
    $language = 'english/';
79
    if (\is_dir(__DIR__ . '/' . $xoopsConfig['language'])) {
80
        $language = $xoopsConfig['language'] . '/';
81
    }
82
83
    // load module tables
84
    foreach ($tables as $table) {
85
        $tabledata = Yaml::readWrapped($language . $table . '.yml');
86
        TableLoad::truncateTable($table);
87
        TableLoad::loadTableFromArray($table, $tabledata);
88
    }
89
90
    // load permissions
91
    $table     = 'group_permission';
92
    $tabledata = Yaml::readWrapped($language . $table . '.yml');
93
    $mid       = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getVar('mid');
94
    loadTableFromArrayWithReplace($table, $tabledata, 'gperm_modid', $mid);
95
96
    //  ---  COPY test folder files ---------------
97
    if (\is_array($configurator->copyTestFolders) && \count($configurator->copyTestFolders) > 0) {
98
        //        $file =  dirname(__DIR__) . '/testdata/images/';
99
        foreach (\array_keys($configurator->copyTestFolders) as $i) {
100
            $src  = $configurator->copyTestFolders[$i][0];
101
            $dest = $configurator->copyTestFolders[$i][1];
102
            $utility::rcopy($src, $dest);
103
        }
104
    }
105
    \redirect_header('../admin/index.php', 1, \constant('CO_' . $moduleDirNameUpper . '_' . 'LOAD_SAMPLEDATA_SUCCESS'));
106
}
107
108
function saveSampleData()
109
{
110
    global $xoopsConfig;
111
    $moduleDirName      = \basename(\dirname(__DIR__));
112
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
113
    $helper             = Helper::getInstance();
114
    $tables             = $helper->getModule()->getInfo('tables');
115
116
    $languageFolder = __DIR__ . '/' . $xoopsConfig['language'];
117
    if (!\file_exists($languageFolder . '/')) {
118
        Utility::createFolder($languageFolder . '/');
119
    }
120
    $exportFolder = $languageFolder . '/Exports-' . date('Y-m-d-H-i-s') . '/';
121
    Utility::createFolder($exportFolder);
122
123
    // save module tables
124
    foreach ($tables as $table) {
125
        TableLoad::saveTableToYamlFile($table, $exportFolder . $table . '.yml');
126
    }
127
128
    // save permissions
129
    $criteria = new \CriteriaCompo();
130
    $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

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