Passed
Push — master ( cd1280...8f08f5 )
by Michael
04:21
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
eloc 25
dl 0
loc 41
rs 8.8977
c 1
b 0
f 0
cc 6
nc 11
nop 4
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
 * @since           2.5.9
13
 * @author          Michael Beck (aka Mamba)
14
 */
15
16
use \Xmf\Request;
17
use XoopsModules\Extcal\{
18
    Helper,
19
    Common,
20
    Utility
21
};
22
23
require_once dirname(__DIR__, 3) . '/include/cp_header.php';
24
require dirname(__DIR__) . '/preloads/autoloader.php';
25
26
$op = Request::getCmd('op', '');
27
28
$moduleDirName      = basename(dirname(__DIR__));
29
$moduleDirNameUpper = mb_strtoupper($moduleDirName);
30
31
$helper = Helper::getInstance();
32
// Load language files
33
$helper->loadLanguage('common');
34
35
switch ($op) {
36
    case 'load':
37
        if (Request::hasVar('ok', 'REQUEST') && 1 === Request::getInt('ok', 0)) {
38
            if (!$GLOBALS['xoopsSecurity']->check()) {
39
                redirect_header('../admin/index.php', 3, implode(',', $GLOBALS['xoopsSecurity']->getErrors()));
40
            }
41
            loadSampleData();
42
        } else {
43
            xoops_cp_header();
44
            xoops_confirm(['ok' => 1, 'op' => 'load'], 'index.php', sprintf(constant('CO_' . $moduleDirNameUpper . '_' . 'ADD_SAMPLEDATA_OK')), constant('CO_' . $moduleDirNameUpper . '_' . 'CONFIRM'), true);
45
            xoops_cp_footer();
46
        }
47
        break;
48
    case 'save':
49
        saveSampleData();
50
        break;
51
}
52
53
// XMF TableLoad for SAMPLE data
54
55
function loadSampleData()
56
{
57
    global $xoopsConfig;
58
    $moduleDirName      = basename(dirname(__DIR__));
59
    $moduleDirNameUpper = mb_strtoupper($moduleDirName);
60
61
    $utility      = new Utility();
62
    $configurator = new Common\Configurator();
63
64
    $tables = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getInfo('tables');
65
66
    $language = 'english/';
67
    if (is_dir(__DIR__ . '/' . $xoopsConfig['language'])) {
68
        $language = $xoopsConfig['language'] . '/';
69
    }
70
71
    // load module tables
72
    foreach ($tables as $table) {
73
        $tabledata = \Xmf\Yaml::readWrapped($language . $table . '.yml');
74
        \Xmf\Database\TableLoad::truncateTable($table);
75
        \Xmf\Database\TableLoad::loadTableFromArray($table, $tabledata);
76
    }
77
78
    // load permissions
79
    $table     = 'group_permission';
80
    $tabledata = \Xmf\Yaml::readWrapped($language . $table . '.yml');
81
    $mid       = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getVar('mid');
82
    loadTableFromArrayWithReplace($table, $tabledata, 'gperm_modid', $mid);
83
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 . '_' . 'SAMPLEDATA_SUCCESS'));
94
}
95
96
function saveSampleData()
97
{
98
    global $xoopsConfig;
99
    $moduleDirName      = basename(dirname(__DIR__));
100
    $moduleDirNameUpper = mb_strtoupper($moduleDirName);
101
102
    $tables = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getInfo('tables');
103
104
    $languageFolder = __DIR__ . '/' . $xoopsConfig['language'];
105
    if (!file_exists($languageFolder . '/')) {
106
        Utility::createFolder($languageFolder . '/');
107
    }
108
    $exportFolder = $languageFolder . '/Exports-' . date('Y-m-d-H-i-s') . '/';
109
    Utility::createFolder($exportFolder);
110
111
    // save module tables
112
    foreach ($tables as $table) {
113
        \Xmf\Database\TableLoad::saveTableToYamlFile($table, $exportFolder . $table . '.yml');
114
    }
115
116
    // save permissions
117
    $criteria = new \CriteriaCompo();
118
    $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

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