loadSampleData()   B
last analyzed

Complexity

Conditions 7
Paths 16

Size

Total Lines 62
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 0 Features 1
Metric Value
cc 7
eloc 41
c 6
b 0
f 1
nc 16
nop 0
dl 0
loc 62
rs 8.3306

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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): https://github.com/mambax7
15
 */
16
17
use Xmf\Database\TableLoad;
18
use Xmf\Database\Tables;
19
use Xmf\Request;
1 ignored issue
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...
20
use Xmf\Yaml;
21
use XoopsModules\Publisher\Common\Configurator;
22
use XoopsModules\Publisher\Helper;
23
use XoopsModules\Publisher\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)
82
                                ->getModule()
83
                                ->getInfo('tables');
84
85
    $language = 'english/';
86
    if (is_dir(__DIR__ . '/' . $xoopsConfig['language'])) {
87
        $language = $xoopsConfig['language'] . '/';
88
    }
89
90
    clearImages();
91
    // load module tables
92
    foreach ($tables as $table) {
93
        $tabledata = Yaml::readWrapped($language . $table . '.yml');
94
        TableLoad::truncateTable($table);
95
        TableLoad::loadTableFromArray($table, $tabledata);
96
    }
97
98
    // load permissions
99
    $table     = 'group_permission';
100
    $tabledata = Yaml::readWrapped($language . $table . '.yml');
101
    $mid       = \Xmf\Module\Helper::getHelper($moduleDirName)
102
                                   ->getModule()
103
                                   ->getVar('mid');
104
    loadTableFromArrayWithReplace($table, $tabledata, 'gperm_modid', $mid);
105
106
    if (1 === $configurator->testimages['images']) {
107
        // load test image categories
108
        $table     = 'imagecategory';
109
        $tabledata = Yaml::readWrapped($language . $table . '.yml');
110
        $mid       = \Xmf\Module\Helper::getHelper($moduleDirName)
111
                                       ->getModule()
112
                                       ->getVar('mid');
113
        loadTableFromArrayWithReplace($table, $tabledata, 'gperm_modid', $mid);
114
115
        // load test images
116
        $table     = 'image';
117
        $tabledata = Yaml::readWrapped($language . $table . '.yml');
118
        $mid       = \Xmf\Module\Helper::getHelper($moduleDirName)
119
                                       ->getModule()
120
                                       ->getVar('mid');
121
        loadTableFromArrayWithReplace($table, $tabledata, 'gperm_modid', $mid);
122
    }
123
124
    //  ---  COPY test folder files ---------------
125
    if ($configurator->copyTestFolders && \is_array($configurator->copyTestFolders)) {
126
        //        $file =  \dirname(__DIR__) . '/testdata/images/';
127
        foreach (array_keys($configurator->copyTestFolders) as $i) {
128
            $src  = $configurator->copyTestFolders[$i][0];
129
            $dest = $configurator->copyTestFolders[$i][1];
130
            $utility::rcopy($src, $dest);
131
        }
132
    }
133
    \redirect_header('../admin/index.php', 1, \constant('CO_' . $moduleDirNameUpper . '_' . 'LOAD_SAMPLEDATA_SUCCESS'));
134
}
135
136
function saveSampleData(): void
137
{
138
    global $xoopsConfig;
139
    $moduleDirName      = \basename(\dirname(__DIR__));
140
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
141
    $helper             = Helper::getInstance();
142
    $tables             = $helper->getModule()
143
                                 ->getInfo('tables');
144
    $configurator       = new Configurator();
145
146
    $languageFolder = __DIR__ . '/' . $xoopsConfig['language'];
147
    if (!file_exists($languageFolder . '/')) {
148
        Utility::createFolder($languageFolder . '/');
149
    }
150
    $exportFolder = $languageFolder . '/Exports-' . date('Y-m-d-H-i-s') . '/';
151
    Utility::createFolder($exportFolder);
152
153
    // save module tables
154
    foreach ($tables as $table) {
155
        TableLoad::saveTableToYamlFile($table, $exportFolder . $table . '.yml');
156
    }
157
158
    // save permissions
159
    $criteria = new \CriteriaCompo();
160
    $criteria->add(
161
        new \Criteria(
162
            'gperm_modid', $helper->getModule()
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

162
            'gperm_modid', /** @scrutinizer ignore-type */ $helper->getModule()
Loading history...
163
                                  ->getVar('mid')
164
        )
165
    );
166
    $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...
167
    TableLoad::saveTableToYamlFile('group_permission', $exportFolder . 'group_permission.yml', $criteria, $skipColumns);
168
    unset($criteria);
169
170
    // save test image category
171
    if (1 === $configurator->testimages['images']) {
172
        $criteria = new \CriteriaCompo();
173
        $criteria->add(new \Criteria('imgcat_name', $configurator->testimages['imgcat_name']));
174
        TableLoad::saveTableToYamlFile('imagecategory', $exportFolder . 'imagecategory.yml', $criteria);
175
        unset($criteria);
176
177
        // save test images
178
        $criteria = new \CriteriaCompo();
179
        $criteria->add(new \Criteria('imgcat_id', $configurator->testimages['imgcat_id']));
180
        TableLoad::saveTableToYamlFile('image', $exportFolder . 'image.yml', $criteria);
181
        unset($criteria);
182
    }
183
184
    \redirect_header('../admin/index.php', 1, \constant('CO_' . $moduleDirNameUpper . '_' . 'SAVE_SAMPLEDATA_SUCCESS'));
185
}
186
187
function exportSchema(): void
188
{
189
    $moduleDirName      = \basename(\dirname(__DIR__));
190
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
0 ignored issues
show
Unused Code introduced by
The assignment to $moduleDirNameUpper is dead and can be removed.
Loading history...
191
192
    try {
193
        // TODO set exportSchema
194
        //        $migrate = new Migrate($moduleDirName);
195
        //        $migrate->saveCurrentSchema();
196
        //
197
        //        redirect_header('../admin/index.php', 1, constant('CO_' . $moduleDirNameUpper . '_' . 'EXPORT_SCHEMA_SUCCESS'));
198
    } 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...
199
        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...
200
    }
201
}
202
203
/**
204
 * loadTableFromArrayWithReplace
205
 *
206
 * @param string $table  value with should be used insead of original value of $search
207
 *
208
 * @param array  $data   array of rows to insert
209
 *                       Each element of the outer array represents a single table row.
210
 *                       Each row is an associative array in 'column' => 'value' format.
211
 * @param string $search name of column for which the value should be replaced
212
 * @param        $replace
213
 * @return int number of rows inserted
214
 */
215
function loadTableFromArrayWithReplace($table, $data, $search, $replace)
216
{
217
    /** @var \XoopsMySQLDatabase $db */
218
    $db = \XoopsDatabaseFactory::getDatabaseConnection();
219
220
    $prefixedTable = $db->prefix($table);
221
    $count         = 0;
222
223
    $sql = 'DELETE FROM ' . $prefixedTable . ' WHERE `' . $search . '`=' . $db->quote($replace);
224
225
    $result = $db->queryF($sql);
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
226
227
    foreach ($data as $row) {
228
        $insertInto  = 'INSERT INTO ' . $prefixedTable . ' (';
229
        $valueClause = ' VALUES (';
230
        $first       = true;
231
        foreach ($row as $column => $value) {
232
            if ($first) {
233
                $first = false;
234
            } else {
235
                $insertInto  .= ', ';
236
                $valueClause .= ', ';
237
            }
238
239
            $insertInto .= $column;
240
            if ($search === $column) {
241
                $valueClause .= $db->quote($replace);
242
            } else {
243
                $valueClause .= $db->quote($value);
244
            }
245
        }
246
247
        $sql = $insertInto . ') ' . $valueClause . ')';
248
249
        $result = $db->queryF($sql);
250
        if (false !== $result) {
251
            ++$count;
252
        }
253
    }
254
255
    return $count;
256
}
257
258
function clearSampleData(): void
259
{
260
    $moduleDirName      = \basename(\dirname(__DIR__));
261
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
262
    $helper             = Helper::getInstance();
263
    // Load language files
264
    $helper->loadLanguage('common');
265
    $tables = $helper->getModule()
266
                     ->getInfo('tables');
267
    // truncate module tables
268
    foreach ($tables as $table) {
269
        \Xmf\Database\TableLoad::truncateTable($table);
270
    }
271
272
    clearImages();
273
274
    redirect_header($helper->url('admin/index.php'), 1, constant('CO_' . $moduleDirNameUpper . '_' . 'CLEAR_SAMPLEDATA_OK'));
275
}
276
277
function clearImages(): void
278
{
279
    $configurator = new Configurator();
280
    // clear test images & image category
281
    if (1 === $configurator->testimages['images']) {
282
        // clear test image category
283
        $criteria = new \CriteriaCompo();
284
        $criteria->add(new \Criteria('imgcat_name', $configurator->testimages['imgcat_name']));
285
        deleteRecords($criteria, 'imagecategory');//::saveTableToYamlFile('imagecategory', $exportFolder . 'imagecategory.yml', $criteria);
286
        unset($criteria);
287
288
        // clear test images
289
        $criteria = new \CriteriaCompo();
290
        $criteria->add(new \Criteria('imgcat_id', $configurator->testimages['imgcat_id']));
291
        deleteRecords($criteria, 'image');
292
        unset($criteria);
293
    }
294
}
295
296
function deleteRecords(?\CriteriaCompo $criteria = null, ?string $table = null): bool
297
{
298
    /** @var \XoopsMySQLDatabase $db */
299
    $db            = \XoopsDatabaseFactory::getDatabaseConnection();
300
    $prefixedTable = $db->prefix($table);
301
    $sql           = 'DELETE FROM ' . $prefixedTable . ' ';
302
    if (isset($criteria) && is_subclass_of($criteria, '\CriteriaElement')) {
303
        /** @var  \CriteriaCompo $criteria */
304
        $sql .= $criteria->renderWhere();
305
    }
306
    $result = $db->queryF($sql);
307
    if ($result) {
308
        return true;
309
    }
310
    return false;
311
}
312