loadTableFromArrayWithReplace()   B
last analyzed

Complexity

Conditions 6
Paths 11

Size

Total Lines 41
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

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

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