clearSampleData()   A
last analyzed

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

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