Passed
Push — master ( 8b5e26...f79285 )
by Michael
04:32
created

loadSampleData()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 39
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 6
eloc 23
nc 8
nop 0
dl 0
loc 39
rs 8.9297
c 3
b 0
f 0
1
<?php
2
/**
3
 * You may not change or alter any portion of this comment or credits
4
 * of supporting developers from this source code or any supporting source code
5
 * which is considered copyrighted (c) material of the original comment or credit authors.
6
 * This program is distributed in the hope that it will be useful,
7
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
8
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
9
 *
10
 * @copyright       The XOOPS Project http://sourceforge.net/projects/xoops/
11
 * @license         GNU GPL 2 (https://www.gnu.org/licenses/old-licenses/gpl-2.0.html)
12
 * @package
13
 * @since           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\Pedigree\{
21
    Helper,
22
    Common\Configurator,
23
    Utility
24
};
25
/** @var Helper $helper */
26
/** @var Utility $utility */
27
/** @var Configurator $configurator */
28
29
require_once dirname(__DIR__, 3) . '/include/cp_header.php';
30
require \dirname(__DIR__) . '/preloads/autoloader.php';
31
32
$op = Request::getCmd('op', '');
33
34
$moduleDirName = \basename(\dirname(__DIR__));
35
$moduleDirNameUpper = \mb_strtoupper($moduleDirName);
36
37
$helper = Helper::getInstance();
38
// Load language files
39
$helper->loadLanguage('common');
40
41
switch ($op) {
42
    case 'load':
43
        if (Request::hasVar('ok', 'REQUEST') && 1 === Request::getInt('ok', 0)) {
44
            if (!$GLOBALS['xoopsSecurity']->check()) {
45
                \redirect_header($helper->url('admin/index.php'), 3, implode(',', $GLOBALS['xoopsSecurity']->getErrors()));
46
            }
47
            loadSampleData();
48
        } else {
49
            xoops_cp_header();
50
            xoops_confirm(['ok' => 1, 'op' => 'load'], 'index.php', \sprintf(\constant('CO_' . $moduleDirNameUpper . '_' . 'LOAD_SAMPLEDATA_CONFIRM')), \constant('CO_' . $moduleDirNameUpper . '_' . 'CONFIRM'), true);
51
            xoops_cp_footer();
52
        }
53
        break;
54
    case 'save':
55
        saveSampleData();
56
        break;
57
    case 'clear':
58
        clearSampleData();
59
        break;
60
}
61
62
// XMF TableLoad for SAMPLE data
63
64
function loadSampleData()
65
{
66
    global $xoopsConfig;
67
    $moduleDirName      = \basename(\dirname(__DIR__));
68
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
69
70
    $utility      = new Utility();
71
    $configurator = new Configurator();
72
73
    $tables = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getInfo('tables');
74
75
    $language = 'english/';
76
    if (\is_dir(__DIR__ . '/' . $xoopsConfig['language'])) {
77
        $language = $xoopsConfig['language'] . '/';
78
    }
79
80
    // load module tables
81
    foreach ($tables as $table) {
82
        $tabledata = Yaml::readWrapped($language . $table . '.yml');
83
        TableLoad::truncateTable($table);
84
        TableLoad::loadTableFromArray($table, $tabledata);
85
    }
86
87
    // load permissions
88
    $table     = 'group_permission';
89
    $tabledata = Yaml::readWrapped($language . $table . '.yml');
90
    $mid       = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getVar('mid');
91
    loadTableFromArrayWithReplace($table, $tabledata, 'gperm_modid', $mid);
92
93
    //  ---  COPY test folder files ---------------
94
    if (\is_array($configurator->copyTestFolders) && \count($configurator->copyTestFolders) > 0) {
95
        //        $file =  dirname(__DIR__) . '/testdata/images/';
96
        foreach (\array_keys($configurator->copyTestFolders) as $i) {
97
            $src  = $configurator->copyTestFolders[$i][0];
98
            $dest = $configurator->copyTestFolders[$i][1];
99
            $utility::rcopy($src, $dest);
100
        }
101
    }
102
    \redirect_header('../admin/index.php', 1, \constant('CO_' . $moduleDirNameUpper . '_' . 'LOAD_SAMPLEDATA_SUCCESS'));
103
}
104
105
function saveSampleData()
106
{
107
    global $xoopsConfig;
108
    $moduleDirName      = \basename(\dirname(__DIR__));
109
    $moduleDirNameUpper = mb_strtoupper($moduleDirName);
110
    $helper             = Helper::getInstance();
111
    $tables             = $helper->getModule()->getInfo('tables');
112
113
    $languageFolder = __DIR__ . '/' . $xoopsConfig['language'];
114
    if (!\file_exists($languageFolder . '/')) {
115
        Utility::createFolder($languageFolder . '/');
116
    }
117
    $exportFolder = $languageFolder . '/Exports-' . date('Y-m-d-H-i-s') . '/';
118
    Utility::createFolder($exportFolder);
119
120
    // save module tables
121
    foreach ($tables as $table) {
122
        TableLoad::saveTableToYamlFile($table, $exportFolder . $table . '.yml');
123
    }
124
125
    // save permissions
126
    $criteria = new \CriteriaCompo();
127
    $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

127
    $criteria->add(new \Criteria('gperm_modid', /** @scrutinizer ignore-type */ $helper->getModule()->getVar('mid')));
Loading history...
128
    $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...
129
    TableLoad::saveTableToYamlFile('group_permission', $exportFolder . 'group_permission.yml', $criteria, $skipColumns);
130
    unset($criteria);
131
132
    \redirect_header('../admin/index.php', 1, \constant('CO_' . $moduleDirNameUpper . '_' . 'SAVE_SAMPLEDATA_SUCCESS'));
133
}
134
135
function exportSchema()
136
{
137
    $moduleDirName      = \basename(\dirname(__DIR__));
138
    $moduleDirNameUpper = mb_strtoupper($moduleDirName);
0 ignored issues
show
Unused Code introduced by
The assignment to $moduleDirNameUpper is dead and can be removed.
Loading history...
139
140
    try {
141
        // TODO set exportSchema
142
        //        $migrate = new Migrate($moduleDirName);
143
        //        $migrate->saveCurrentSchema();
144
        //
145
        //        redirect_header('../admin/index.php', 1, constant('CO_' . $moduleDirNameUpper . '_' . 'EXPORT_SCHEMA_SUCCESS'));
146
    } 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...
147
        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...
148
    }
149
}
150
151
/**
152
 * loadTableFromArrayWithReplace
153
 *
154
 * @param string $table  value with should be used insead of original value of $search
155
 *
156
 * @param array  $data   array of rows to insert
157
 *                       Each element of the outer array represents a single table row.
158
 *                       Each row is an associative array in 'column' => 'value' format.
159
 * @param string $search name of column for which the value should be replaced
160
 * @param        $replace
161
 * @return int number of rows inserted
162
 */
163
function loadTableFromArrayWithReplace($table, $data, $search, $replace)
164
{
165
    /** @var \XoopsMySQLDatabase $db */
166
    $db = \XoopsDatabaseFactory::getDatabaseConnection();
167
168
    $prefixedTable = $db->prefix($table);
169
    $count         = 0;
170
171
    $sql = 'DELETE FROM ' . $prefixedTable . ' WHERE `' . $search . '`=' . $db->quote($replace);
172
173
    $result = $db->queryF($sql);
174
175
    if ($result) {
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()
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