Passed
Push — master ( 84997c...4c3a31 )
by Michael
03:04
created

loadTableFromArrayWithReplace()   B

Complexity

Conditions 6
Paths 11

Size

Total Lines 41
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

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

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