loadSampleData()   B
last analyzed

Complexity

Conditions 6
Paths 8

Size

Total Lines 39
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 6
eloc 23
c 2
b 1
f 0
nc 8
nop 0
dl 0
loc 39
rs 8.9297
1
<?php declare(strict_types=1);
2
3
/**
4
 * You may not change or alter any portion of this comment or credits
5
 * of supporting developers from this source code or any supporting source code
6
 * which is considered copyrighted (c) material of the original comment or credit authors.
7
 * This program is distributed in the hope that it will be useful,
8
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10
 *
11
 * @copyright       XOOPS Project (https://xoops.org)
12
 * @license         GNU GPL 2 (https://www.gnu.org/licenses/old-licenses/gpl-2.0.html)
13
 * @since           2.5.9
14
 * @author          Michael Beck (aka Mamba)
15
 */
16
17
use Xmf\Database\TableLoad;
18
use Xmf\Request;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Request. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
19
use Xmf\Yaml;
20
use XoopsModules\News\{
21
    Common\Configurator,
22
    Helper,
23
    Utility
24
};
25
/** @var Helper $helper */
26
/** @var Utility $utility */
27
/** @var Configurator $configurator */
28
require \dirname(__DIR__, 3) . '/include/cp_header.php';
29
require \dirname(__DIR__) . '/preloads/autoloader.php';
30
31
$op = Request::getCmd('op', '');
32
33
$moduleDirName      = \basename(\dirname(__DIR__));
34
$moduleDirNameUpper = \mb_strtoupper($moduleDirName);
35
36
$helper = Helper::getInstance();
37
// Load language files
38
$helper->loadLanguage('common');
39
40
switch ($op) {
41
    case 'load':
42
        if (Request::hasVar('ok', 'REQUEST') && 1 === Request::getInt('ok', 0)) {
43
            if (!$GLOBALS['xoopsSecurity']->check()) {
44
                redirect_header($helper->url('admin/index.php'), 3, implode(',', $GLOBALS['xoopsSecurity']->getErrors()));
45
            }
46
            loadSampleData();
47
        } else {
48
            xoops_cp_header();
49
            xoops_confirm(['ok' => 1, 'op' => 'load'], 'index.php', constant('CO_' . $moduleDirNameUpper . '_' . 'LOAD_SAMPLEDATA_CONFIRM'), constant('CO_' . $moduleDirNameUpper . '_' . 'CONFIRM'), true);
50
            xoops_cp_footer();
51
        }
52
        break;
53
    case 'save':
54
        saveSampleData();
55
        break;
56
    case 'clear':
57
        if (Request::hasVar('ok', 'REQUEST') && 1 === Request::getInt('ok', 0)) {
58
            if (!$GLOBALS['xoopsSecurity']->check()) {
59
                redirect_header($helper->url('admin/index.php'), 3, implode(',', $GLOBALS['xoopsSecurity']->getErrors()));
60
            }
61
            clearSampleData();
62
        } else {
63
            xoops_cp_header();
64
            xoops_confirm(['ok' => 1, 'op' => 'clear'], 'index.php', sprintf(constant('CO_' . $moduleDirNameUpper . '_' . 'CLEAR_SAMPLEDATA')), constant('CO_' . $moduleDirNameUpper . '_' . 'CONFIRM'), true);
65
            xoops_cp_footer();
66
        }
67
        break;
68
}
69
70
// XMF TableLoad for SAMPLE data
71
72
function loadSampleData(): void
73
{
74
    global $xoopsConfig;
75
    $moduleDirName      = \basename(\dirname(__DIR__));
76
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
77
78
    $utility      = new Utility();
79
    $configurator = new Configurator();
80
81
    $tables = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getInfo('tables');
82
83
    $language = 'english/';
84
    if (is_dir(__DIR__ . '/' . $xoopsConfig['language'])) {
85
        $language = $xoopsConfig['language'] . '/';
86
    }
87
88
    // load module tables
89
    foreach ($tables as $table) {
90
        $tabledata = Yaml::readWrapped($language . $table . '.yml');
91
        TableLoad::truncateTable($table);
92
        TableLoad::loadTableFromArray($table, $tabledata);
93
    }
94
95
    // load permissions
96
    $table     = 'group_permission';
97
    $tabledata = Yaml::readWrapped($language . $table . '.yml');
98
    $mid       = \Xmf\Module\Helper::getHelper($moduleDirName)->getModule()->getVar('mid');
99
    loadTableFromArrayWithReplace($table, $tabledata, 'gperm_modid', $mid);
100
101
    //  ---  COPY test folder files ---------------
102
    if (is_array($configurator->copyTestFolders) && count($configurator->copyTestFolders) > 0) {
103
        //        $file =  \dirname(__DIR__) . '/testdata/images/';
104
        foreach (array_keys($configurator->copyTestFolders) as $i) {
105
            $src  = $configurator->copyTestFolders[$i][0];
106
            $dest = $configurator->copyTestFolders[$i][1];
107
            $utility::rcopy($src, $dest);
108
        }
109
    }
110
    \redirect_header('../admin/index.php', 1, \constant('CO_' . $moduleDirNameUpper . '_' . 'LOAD_SAMPLEDATA_SUCCESS'));
111
}
112
113
function saveSampleData(): void
114
{
115
    global $xoopsConfig;
116
    $moduleDirName      = \basename(\dirname(__DIR__));
117
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
118
    $helper             = Helper::getInstance();
119
    $tables             = $helper->getModule()->getInfo('tables');
120
121
    $languageFolder = __DIR__ . '/' . $xoopsConfig['language'];
122
    if (!file_exists($languageFolder . '/')) {
123
        Utility::createFolder($languageFolder . '/');
124
    }
125
    $exportFolder = $languageFolder . '/Exports-' . date('Y-m-d-H-i-s') . '/';
126
    Utility::createFolder($exportFolder);
127
128
    // save module tables
129
    foreach ($tables as $table) {
130
        TableLoad::saveTableToYamlFile($table, $exportFolder . $table . '.yml');
131
    }
132
133
    // save permissions
134
    $criteria = new \CriteriaCompo();
135
    $criteria->add(new \Criteria('gperm_modid', $helper->getModule()->getVar('mid')));
0 ignored issues
show
Bug introduced by
It seems like $helper->getModule()->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

135
    $criteria->add(new \Criteria('gperm_modid', /** @scrutinizer ignore-type */ $helper->getModule()->getVar('mid')));
Loading history...
136
    $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...
137
    TableLoad::saveTableToYamlFile('group_permission', $exportFolder . 'group_permission.yml', $criteria, $skipColumns);
138
    unset($criteria);
139
140
    \redirect_header('../admin/index.php', 1, \constant('CO_' . $moduleDirNameUpper . '_' . 'SAVE_SAMPLEDATA_SUCCESS'));
141
}
142
143
function exportSchema(): void
144
{
145
    $moduleDirName      = \basename(\dirname(__DIR__));
146
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
0 ignored issues
show
Unused Code introduced by
The assignment to $moduleDirNameUpper is dead and can be removed.
Loading history...
147
148
    try {
149
        // TODO set exportSchema
150
        //        $migrate = new Migrate($moduleDirName);
151
        //        $migrate->saveCurrentSchema();
152
        //
153
        //        redirect_header('../admin/index.php', 1, constant('CO_' . $moduleDirNameUpper . '_' . 'EXPORT_SCHEMA_SUCCESS'));
154
    } 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...
155
        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...
156
    }
157
}
158
159
/**
160
 * loadTableFromArrayWithReplace
161
 *
162
 * @param string $table  value with should be used insead of original value of $search
163
 *
164
 * @param array  $data   array of rows to insert
165
 *                       Each element of the outer array represents a single table row.
166
 *                       Each row is an associative array in 'column' => 'value' format.
167
 * @param string $search name of column for which the value should be replaced
168
 * @param        $replace
169
 * @return int number of rows inserted
170
 */
171
function loadTableFromArrayWithReplace($table, $data, $search, $replace)
172
{
173
    /** @var \XoopsMySQLDatabase $db */
174
    $db = \XoopsDatabaseFactory::getDatabaseConnection();
175
176
    $prefixedTable = $db->prefix($table);
177
    $count         = 0;
178
179
    $sql = 'DELETE FROM ' . $prefixedTable . ' WHERE `' . $search . '`=' . $db->quote($replace);
180
181
    $result = $db->queryF($sql);
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
182
183
    foreach ($data as $row) {
184
        $insertInto  = 'INSERT INTO ' . $prefixedTable . ' (';
185
        $valueClause = ' VALUES (';
186
        $first       = true;
187
        foreach ($row as $column => $value) {
188
            if ($first) {
189
                $first = false;
190
            } else {
191
                $insertInto  .= ', ';
192
                $valueClause .= ', ';
193
            }
194
195
            $insertInto .= $column;
196
            if ($search === $column) {
197
                $valueClause .= $db->quote($replace);
198
            } else {
199
                $valueClause .= $db->quote($value);
200
            }
201
        }
202
203
        $sql = $insertInto . ') ' . $valueClause . ')';
204
205
        $result = $db->queryF($sql);
206
        if (false !== $result) {
207
            ++$count;
208
        }
209
    }
210
211
    return $count;
212
}
213
214
function clearSampleData(): void
215
{
216
    $moduleDirName      = \basename(\dirname(__DIR__));
217
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
218
    $helper             = Helper::getInstance();
219
    // Load language files
220
    $helper->loadLanguage('common');
221
    $tables = $helper->getModule()->getInfo('tables');
222
    // truncate module tables
223
    foreach ($tables as $table) {
224
        \Xmf\Database\TableLoad::truncateTable($table);
225
    }
226
    redirect_header($helper->url('admin/index.php'), 1, constant('CO_' . $moduleDirNameUpper . '_' . 'CLEAR_SAMPLEDATA_OK'));
227
}
228