Passed
Push — master ( da394c...44937f )
by Michael
05:20
created

loadSampleData()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 33
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 23
nc 8
nop 0
dl 0
loc 33
rs 8.9297
c 1
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 Xmf\Yaml;
20
use XoopsModules\Marquee\{Helper,
21
    Common\Configurator,
22
    Utility
23
};
24
25
require_once dirname(__DIR__, 3) . '/include/cp_header.php';
26
require dirname(__DIR__) . '/preloads/autoloader.php';
27
$op = Request::getCmd('op', '');
28
$moduleDirName      = basename(dirname(__DIR__));
29
$moduleDirNameUpper = mb_strtoupper($moduleDirName);
30
$helper = Helper::getInstance();
31
// Load language files
32
$helper->loadLanguage('common');
33
switch ($op) {
34
    case 'load':
35
        if (Request::hasVar('ok', 'REQUEST') && 1 === Request::getInt('ok', 0)) {
36
            if (!$GLOBALS['xoopsSecurity']->check()) {
37
                redirect_header($helper->url('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
// XMF TableLoad for SAMPLE data
51
function loadSampleData()
52
{
53
    global $xoopsConfig;
54
    $moduleDirName      = basename(dirname(__DIR__));
55
    $moduleDirNameUpper = mb_strtoupper($moduleDirName);
56
    $utility      = new Utility();
57
    $configurator = new Configurator();
58
    $tables = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getInfo('tables');
59
    $language = 'english/';
60
    if (is_dir(__DIR__ . '/' . $xoopsConfig['language'])) {
61
        $language = $xoopsConfig['language'] . '/';
62
    }
63
    // load module tables
64
    foreach ($tables as $table) {
65
        $tabledata = Yaml::readWrapped($language . $table . '.yml');
66
        TableLoad::truncateTable($table);
67
        TableLoad::loadTableFromArray($table, $tabledata);
68
    }
69
    // load permissions
70
    $table     = 'group_permission';
71
    $tabledata = Yaml::readWrapped($language . $table . '.yml');
72
    $mid       = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getVar('mid');
73
    loadTableFromArrayWithReplace($table, $tabledata, 'gperm_modid', $mid);
74
    //  ---  COPY test folder files ---------------
75
    if (is_array($configurator->copyTestFolders) && count($configurator->copyTestFolders) > 0) {
76
        //        $file =  dirname(__DIR__) . '/testdata/images/';
77
        foreach (array_keys($configurator->copyTestFolders) as $i) {
78
            $src  = $configurator->copyTestFolders[$i][0];
79
            $dest = $configurator->copyTestFolders[$i][1];
80
            $utility::rcopy($src, $dest);
81
        }
82
    }
83
    redirect_header('../admin/index.php', 1, constant('CO_' . $moduleDirNameUpper . '_' . 'SAMPLEDATA_SUCCESS'));
84
}
85
86
function saveSampleData()
87
{
88
    global $xoopsConfig;
89
    $moduleDirName      = basename(dirname(__DIR__));
90
    $moduleDirNameUpper = mb_strtoupper($moduleDirName);
91
    $tables = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getInfo('tables');
92
    $languageFolder = __DIR__ . '/' . $xoopsConfig['language'];
93
    if (!file_exists($languageFolder . '/')) {
94
        Utility::createFolder($languageFolder . '/');
95
    }
96
    $exportFolder = $languageFolder . '/Exports-' . date('Y-m-d-H-i-s') . '/';
97
    Utility::createFolder($exportFolder);
98
    // save module tables
99
    foreach ($tables as $table) {
100
        TableLoad::saveTableToYamlFile($table, $exportFolder . $table . '.yml');
101
    }
102
    // save permissions
103
    $criteria = new \CriteriaCompo();
104
    $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

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