saveSampleData()   B
last analyzed

Complexity

Conditions 6
Paths 8

Size

Total Lines 39
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 6
eloc 23
nc 8
nop 0
dl 0
loc 39
rs 8.9297
c 1
b 0
f 1
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 XoopsModules\Tdmcreate;
18
use XoopsModules\Tdmcreate\Common;
19
use XoopsModules\Tdmcreate\Utility;
20
21
require_once dirname(dirname(dirname(__DIR__))) . '/include/cp_header.php';
22
require dirname(__DIR__) . '/preloads/autoloader.php';
23
24
$op = \Xmf\Request::getCmd('op', '');
25
26
$moduleDirName = basename(dirname(__DIR__));
27
$moduleDirNameUpper = mb_strtoupper($moduleDirName);
28
29
$helper = Tdmcreate\Helper::getInstance();
30
// Load language files
31
$helper->loadLanguage('common');
32
33
switch ($op) {
34
    case 'load':
35
        if (\Xmf\Request::hasVar('ok', 'REQUEST') && 1 == $_REQUEST['ok']) {
36
            if (!$GLOBALS['xoopsSecurity']->check()) {
37
                redirect_header('../admin/index.php', 3, implode(',', $GLOBALS['xoopsSecurity']->getErrors()));
38
            }
39
            loadSampleData();
40
        } else {
41
            xoops_cp_header();
42
            xoops_confirm(['ok' => 1, 'op' => 'load'], 'index.php', sprintf(constant('CO_' . $moduleDirNameUpper . '_' . 'ADD_SAMPLEDATA_OK')), constant('CO_' . $moduleDirNameUpper . '_' . 'CONFIRM'), true);
43
            xoops_cp_footer();
44
        }
45
        break;
46
    case 'save':
47
        saveSampleData();
48
        break;
49
}
50
51
// XMF TableLoad for SAMPLE data
52
53
function loadSampleData()
54
{
55
    global $xoopsConfig;
56
57
    $moduleDirName = basename(dirname(__DIR__));
58
    $moduleDirNameUpper = mb_strtoupper($moduleDirName);
59
60
    $utility      = new Tdmcreate\Utility();
61
    $configurator = new Common\Configurator();
62
63
    $tables = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getInfo('tables');
64
65
    $language = 'english/';
66
    if (is_dir(__DIR__ . '/' . $xoopsConfig['language'])) {
67
        $language = $xoopsConfig['language'] . '/';
68
    }
69
70
	// load module tables
71
    foreach ($tables as $table) {
72
        $tabledata = \Xmf\Yaml::readWrapped($language . $table . '.yml');
73
        \Xmf\Database\TableLoad::truncateTable($table);
74
        \Xmf\Database\TableLoad::loadTableFromArray($table, $tabledata);
75
    }
76
	
77
	// load permissions
78
    $table     = 'group_permission';
79
    $tabledata = \Xmf\Yaml::readWrapped($language . $table . '.yml');
80
    $mid       = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getVar('mid');
81
    loadTableFromArrayWithReplace($table, $tabledata, 'gperm_modid', $mid);
82
83
    //  ---  COPY test folder files ---------------
84
    if (is_array($configurator->copyTestFolders) && count($configurator->copyTestFolders) > 0) {
85
        //        $file = __DIR__ . '/../testdata/images/';
86
        foreach (array_keys($configurator->copyTestFolders) as $i) {
87
            $src  = $configurator->copyTestFolders[$i][0];
88
            $dest = $configurator->copyTestFolders[$i][1];
89
            $utility::rcopy($src, $dest);
90
        }
91
    }
92
    redirect_header('../admin/index.php', 1, constant('CO_' . $moduleDirNameUpper . '_' . 'SAMPLEDATA_SUCCESS'));
93
}
94
95
function saveSampleData()
96
{
97
    global $xoopsConfig;
98
    
99
    $configurator = new Common\Configurator();
100
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
        \Xmf\Database\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
    \Xmf\Database\TableLoad::saveTableToYamlFile('group_permission', $exportFolder . 'group_permission.yml', $criteria, $skipColumns);
123
    unset($criteria);
124
    
125
    //  ---  COPY test folder files ---------------
126
    if (is_array($configurator->copyTestFolders) && count($configurator->copyTestFolders) > 0) {
127
        foreach (array_keys($configurator->copyTestFolders) as $i) {
128
            $src  = $configurator->copyTestFolders[$i][1];
129
            $dest = $configurator->copyTestFolders[$i][0];
130
            Utility::rcopy($src, $dest);
131
        }
132
    }
133
    redirect_header('../admin/index.php', 1, constant('CO_' . $moduleDirNameUpper . '_' . 'SAMPLEDATA_SUCCESS'));
134
}
135
136
function exportSchema()
137
{
138
    $moduleDirName      = basename(dirname(__DIR__));
139
    $moduleDirNameUpper = mb_strtoupper($moduleDirName);
0 ignored issues
show
Unused Code introduced by
The assignment to $moduleDirNameUpper is dead and can be removed.
Loading history...
140
141
    try {
142
        // TODO set exportSchema
143
        //        $migrate = new Tdmcreate\Migrate($moduleDirName);
144
        //        $migrate->saveCurrentSchema();
145
        //
146
        //        redirect_header('../admin/index.php', 1, constant('CO_' . $moduleDirNameUpper . '_' . 'EXPORT_SCHEMA_SUCCESS'));
147
    }
148
    catch (\Exception $e) {
0 ignored issues
show
Unused Code introduced by
catch (\Exception $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...
149
        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...
150
    }
151
152
}
153
154
/**
155
 * loadTableFromArrayWithReplace
156
 *
157
 * @param string $table  value with should be used insead of original value of $search
158
 *
159
 * @param array  $data   array of rows to insert
160
 *                       Each element of the outer array represents a single table row.
161
 *                       Each row is an associative array in 'column' => 'value' format.
162
 * @param string $search name of column for which the value should be replaced
163
 * @param        $replace
164
 * @return int number of rows inserted
165
 */
166
function loadTableFromArrayWithReplace($table, $data, $search, $replace)
167
{
168
    /** @var \XoopsDatabase */
169
    $db = \XoopsDatabaseFactory::getDatabaseConnection();
170
171
    $prefixedTable = $db->prefix($table);
172
    $count         = 0;
173
174
    $sql = 'DELETE FROM ' . $prefixedTable . ' WHERE `' . $search . '`=' . $db->quote($replace);
175
176
    $result = $db->queryF($sql);
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
177
178
    foreach ($data as $row) {
179
        $insertInto  = 'INSERT INTO ' . $prefixedTable . ' (';
180
        $valueClause = ' VALUES (';
181
        $first       = true;
182
        foreach ($row as $column => $value) {
183
            if ($first) {
184
                $first = false;
185
            } else {
186
                $insertInto  .= ', ';
187
                $valueClause .= ', ';
188
            }
189
190
            $insertInto .= $column;
191
            if ($search === $column) {
192
                $valueClause .= $db->quote($replace);
193
            } else {
194
                $valueClause .= $db->quote($value);
195
            }
196
        }
197
198
        $sql = $insertInto . ') ' . $valueClause . ')';
199
200
        $result = $db->queryF($sql);
201
        if (false !== $result) {
202
            ++$count;
203
        }
204
    }
205
206
    return $count;
207
}
208