exportSchema()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 13
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 5
c 2
b 0
f 0
dl 0
loc 13
rs 10
cc 2
nc 1
nop 0
1
<?php declare(strict_types=1);
2
3
/**
4
 * You may not change or alter any portion of this comment or credits
5
 * of supporting developers from this source code or any supporting source code
6
 * which is considered copyrighted (c) material of the original comment or credit authors.
7
 * This program is distributed in the hope that it will be useful,
8
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10
 *
11
 * @copyright       XOOPS Project (https://xoops.org)/
12
 * @license         GNU GPL 2 (https://www.gnu.org/licenses/old-licenses/gpl-2.0.html)
13
 * 2.5.9
14
 * @author          Michael Beck (aka Mamba)
15
 */
16
17
use Xmf\Database\TableLoad;
18
use Xmf\Request;
19
use Xmf\Yaml;
20
use XoopsModules\Adslight\Common\Configurator;
21
use XoopsModules\Adslight\Helper;
22
use XoopsModules\Adslight\Utility;
23
24
/** @var Helper $helper */
25
/** @var Utility $utility */
26
/** @var Configurator $configurator */
27
require_once \dirname(__DIR__, 3) . '/include/cp_header.php';
28
require \dirname(__DIR__) . '/preloads/autoloader.php';
29
30
$op = Request::getCmd('op', '');
31
32
$moduleDirName      = \basename(\dirname(__DIR__));
33
$moduleDirNameUpper = \mb_strtoupper($moduleDirName);
34
35
$helper = Helper::getInstance();
36
// Load language files
37
$helper->loadLanguage('common');
38
39
switch ($op) {
40
    case 'load':
41
        if (Request::hasVar('ok', 'REQUEST') && 1 === Request::getInt('ok', 0)) {
42
            if (!$GLOBALS['xoopsSecurity']->check()) {
43
                \redirect_header($helper->url('admin/index.php'), 3, implode(',', $GLOBALS['xoopsSecurity']->getErrors()));
44
            }
45
            loadSampleData();
46
        } else {
47
            xoops_cp_header();
48
            xoops_confirm(['ok' => 1, 'op' => 'load'], 'index.php', \constant('CO_' . $moduleDirNameUpper . '_' . 'LOAD_SAMPLEDATA_CONFIRM'), \constant('CO_' . $moduleDirNameUpper . '_' . 'CONFIRM'), true);
49
            xoops_cp_footer();
50
        }
51
        break;
52
    case 'save':
53
        saveSampleData();
54
        break;
55
    case 'clear':
56
        if (Request::hasVar('ok', 'REQUEST') && 1 === Request::getInt('ok', 0)) {
57
            if (!$GLOBALS['xoopsSecurity']->check()) {
58
                redirect_header($helper->url('admin/index.php'), 3, implode(',', $GLOBALS['xoopsSecurity']->getErrors()));
59
            }
60
            clearSampleData();
61
        } else {
62
            xoops_cp_header();
63
            xoops_confirm(['ok' => 1, 'op' => 'clear'], 'index.php', sprintf(constant('CO_' . $moduleDirNameUpper . '_' . 'CLEAR_SAMPLEDATA')), constant('CO_' . $moduleDirNameUpper . '_' . 'CONFIRM'), true);
64
            xoops_cp_footer();
65
        }
66
        break;
67
}
68
69
// XMF TableLoad for SAMPLE data
70
71
function loadSampleData(): void
72
{
73
    global $xoopsConfig;
74
    $moduleDirName      = \basename(\dirname(__DIR__));
75
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
76
77
    $utility      = new Utility();
78
    $configurator = new Configurator();
79
80
    $tables = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getInfo('tables');
81
82
    $language = 'english/';
83
    if (\is_dir(__DIR__ . '/' . $xoopsConfig['language'])) {
84
        $language = $xoopsConfig['language'] . '/';
85
    }
86
87
    // load module tables
88
    foreach ($tables as $table) {
89
        $tabledata = Yaml::readWrapped($language . $table . '.yml');
90
        TableLoad::truncateTable($table);
91
        TableLoad::loadTableFromArray($table, $tabledata);
92
    }
93
94
    // load permissions
95
    $table     = 'group_permission';
96
    $tabledata = Yaml::readWrapped($language . $table . '.yml');
97
    $mid       = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getVar('mid');
98
    loadTableFromArrayWithReplace($table, $tabledata, 'gperm_modid', $mid);
99
100
    //  ---  COPY test folder files ---------------
101
    if (\is_array($configurator->copyTestFolders) && \count($configurator->copyTestFolders) > 0) {
102
        //        $file =  \dirname(__DIR__) . '/testdata/images/';
103
        foreach (\array_keys($configurator->copyTestFolders) as $i) {
104
            $src  = $configurator->copyTestFolders[$i][0];
105
            $dest = $configurator->copyTestFolders[$i][1];
106
            $utility::rcopy($src, $dest);
107
        }
108
    }
109
    \redirect_header('../admin/index.php', 1, \constant('CO_' . $moduleDirNameUpper . '_' . 'LOAD_SAMPLEDATA_SUCCESS'));
110
}
111
112
function saveSampleData(): void
113
{
114
    global $xoopsConfig;
115
    $moduleDirName      = \basename(\dirname(__DIR__));
116
    $moduleDirNameUpper = mb_strtoupper($moduleDirName);
117
    $helper             = Helper::getInstance();
118
    $tables             = $helper->getModule()->getInfo('tables');
119
120
    $languageFolder = __DIR__ . '/' . $xoopsConfig['language'];
121
    if (!\file_exists($languageFolder . '/')) {
122
        Utility::createFolder($languageFolder . '/');
123
    }
124
    $exportFolder = $languageFolder . '/Exports-' . date('Y-m-d-H-i-s') . '/';
125
    Utility::createFolder($exportFolder);
126
127
    // save module tables
128
    foreach ($tables as $table) {
129
        TableLoad::saveTableToYamlFile($table, $exportFolder . $table . '.yml');
130
    }
131
132
    // save permissions
133
    $criteria = new \CriteriaCompo();
134
    $criteria->add(new \Criteria('gperm_modid', (string)$helper->getModule()->getVar('mid')));
135
    $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...
136
    TableLoad::saveTableToYamlFile('group_permission', $exportFolder . 'group_permission.yml', $criteria, $skipColumns);
137
    unset($criteria);
138
139
    \redirect_header('../admin/index.php', 1, \constant('CO_' . $moduleDirNameUpper . '_' . 'SAVE_SAMPLEDATA_SUCCESS'));
140
}
141
142
function exportSchema(): void
143
{
144
    $moduleDirName      = \basename(\dirname(__DIR__));
145
    $moduleDirNameUpper = mb_strtoupper($moduleDirName);
0 ignored issues
show
Unused Code introduced by
The assignment to $moduleDirNameUpper is dead and can be removed.
Loading history...
146
147
    try {
148
        // TODO set exportSchema
149
        //        $migrate = new Migrate($moduleDirName);
150
        //        $migrate->saveCurrentSchema();
151
        //
152
        //        redirect_header('../admin/index.php', 1, constant('CO_' . $moduleDirNameUpper . '_' . 'EXPORT_SCHEMA_SUCCESS'));
153
    } 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...
154
        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...
155
    }
156
}
157
158
/**
159
 * loadTableFromArrayWithReplace
160
 *
161
 * @param string $table  value which should be used instead of original value of $search
162
 *
163
 * @param array  $data   array of rows to insert
164
 *                       Each element of the outer array represents a single table row.
165
 *                       Each row is an associative array in 'column' => 'value' format.
166
 * @param string $search name of column for which the value should be replaced
167
 * @param        $replace
168
 * @return int number of rows inserted
169
 */
170
function loadTableFromArrayWithReplace($table, $data, $search, $replace): int
171
{
172
    /** @var \XoopsMySQLDatabase $db */
173
    $db = \XoopsDatabaseFactory::getDatabaseConnection();
174
175
    $prefixedTable = $db->prefix($table);
176
    $count         = 0;
177
178
    $sql = 'DELETE FROM ' . $prefixedTable . ' WHERE `' . $search . '`=' . $db->quote($replace);
179
180
    $result = $db->queryF($sql);
181
182
    if ($result) {
183
        foreach ($data as $row) {
184
            $insertInto  = 'INSERT INTO ' . $prefixedTable . ' (';
185
            $valueClause = ' VALUES (';
186
            $first       = true;
187
            foreach ($row as $column => $value) {
188
                if ($first) {
189
                    $first = false;
190
                } else {
191
                    $insertInto  .= ', ';
192
                    $valueClause .= ', ';
193
                }
194
195
                $insertInto .= $column;
196
                if ($search === $column) {
197
                    $valueClause .= $db->quote($replace);
198
                } else {
199
                    $valueClause .= $db->quote($value);
200
                }
201
            }
202
203
            $sql = $insertInto . ') ' . $valueClause . ')';
204
205
            $result = $db->queryF($sql);
206
            if (false !== $result) {
207
                ++$count;
208
            }
209
        }
210
    }
211
212
    return $count;
213
}
214
215
function clearSampleData(): void
216
{
217
    $moduleDirName      = \basename(\dirname(__DIR__));
218
    $moduleDirNameUpper = mb_strtoupper($moduleDirName);
219
    $helper             = Helper::getInstance();
220
    // Load language files
221
    $helper->loadLanguage('common');
222
    $tables = $helper->getModule()->getInfo('tables');
223
    // truncate module tables
224
    foreach ($tables as $table) {
225
        \Xmf\Database\TableLoad::truncateTable($table);
226
    }
227
    redirect_header($helper->url('admin/index.php'), 1, constant('CO_' . $moduleDirNameUpper . '_' . 'CLEAR_SAMPLEDATA_OK'));
228
}
229