loadTableFromArrayWithReplace()   B
last analyzed

Complexity

Conditions 6
Paths 11

Size

Total Lines 34
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 25
c 1
b 0
f 0
nc 11
nop 4
dl 0
loc 34
rs 8.8977
1
<?php
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
 * @package
14
 * @since           2.5.11
15
 * @author          Michael Beck (aka Mamba)
16
 */
17
18
use Xmf\Database\TableLoad;
19
use Xmf\Module\Helper;
20
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...
21
use Xmf\Yaml;
22
use XoopsModules\Wgevents;
23
use XoopsModules\Wgevents\{
24
    Common,
25
    Utility
26
};
27
28
require_once \dirname(__DIR__, 3) . '/include/cp_header.php';
29
require \dirname(__DIR__) . '/preloads/autoloader.php';
30
31
$op = \Xmf\Request::getCmd('op');
32
33
$moduleDirName = \basename(\dirname(__DIR__));
34
$moduleDirNameUpper = \mb_strtoupper($moduleDirName);
35
36
$helper = Wgevents\Helper::getInstance();
37
// Load language files
38
$helper->loadLanguage('common');
39
40
switch ($op) {
41
    case 'load':
42
        if (\Xmf\Request::hasVar('ok', 'REQUEST') && 1 === (int)$_REQUEST['ok']) {
43
            if (!$GLOBALS['xoopsSecurity']->check()) {
44
                \redirect_header('../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 . '_' . 'ADD_SAMPLEDATA_OK'), \constant('CO_' . $moduleDirNameUpper . '_' . 'CONFIRM'));
50
            xoops_cp_footer();
51
        }
52
        break;
53
    case 'save':
54
        saveSampleData();
55
        break;
56
}
57
58
// XMF TableLoad for SAMPLE data
59
/**
60
 * @return void
61
 */
62
function loadSampleData()
63
{
64
    global $xoopsConfig;
65
66
    $moduleDirName      = \basename(\dirname(__DIR__));
67
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
68
69
    $utility      = new Wgevents\Utility();
70
    $configurator = new Common\Configurator();
71
72
    $tables = Helper::getHelper($moduleDirName)->getModule()->getInfo('tables');
73
74
    $language = 'english/';
75
    if (\is_dir(__DIR__ . '/' . $xoopsConfig['language'])) {
76
        $language = $xoopsConfig['language'] . '/';
77
    }
78
79
    // load module tables
80
    foreach ($tables as $table) {
81
        $tabledata = Yaml::readWrapped($language . $table . '.yml');
82
        TableLoad::truncateTable($table);
83
        TableLoad::loadTableFromArray($table, $tabledata);
84
    }
85
86
    // load permissions
87
    $table     = 'group_permission';
88
    $tabledata = Yaml::readWrapped($language . $table . '.yml');
89
    $mid       = Helper::getHelper($moduleDirName)->getModule()->getVar('mid');
90
    loadTableFromArrayWithReplace($table, $tabledata, 'gperm_modid', $mid);
91
92
    //  ---  COPY test folder files ---------------
93
    if (\is_array($configurator->copyTestFolders) && \count($configurator->copyTestFolders) > 0) {
94
        foreach (\array_keys($configurator->copyTestFolders) as $i) {
95
            $src  = $configurator->copyTestFolders[$i][0];
96
            $dest = $configurator->copyTestFolders[$i][1];
97
            $utility::rcopy($src, $dest);
98
        }
99
    }
100
    \redirect_header('../admin/index.php', 1, \constant('CO_' . $moduleDirNameUpper . '_' . 'SAMPLEDATA_SUCCESS'));
101
}
102
103
/**
104
 * @return void
105
 */
106
function saveSampleData()
107
{
108
    global $xoopsConfig;
109
110
    $configurator = new Common\Configurator();
111
112
    $moduleDirName      = \basename(\dirname(__DIR__));
113
    $moduleDirNameUpper = \mb_strtoupper($moduleDirName);
114
115
    $tables = Helper::getHelper($moduleDirName)->getModule()->getInfo('tables');
116
117
    $languageFolder = __DIR__ . '/' . $xoopsConfig['language'];
118
    if (!\file_exists($languageFolder . '/')) {
119
        Utility::createFolder($languageFolder . '/');
120
    }
121
    $exportFolder = $languageFolder . '/Exports-' . date('Y-m-d-H-i-s') . '/';
122
    Utility::createFolder($exportFolder);
123
124
    // save module tables
125
    $tablesNoData = ['wgevents_account'];
126
    foreach ($tables as $table) {
127
        if (in_array($table, $tablesNoData)) {
128
            \file_put_contents($exportFolder . '/' . $table . '.yml', '{}');
129
        } else {
130
            TableLoad::saveTableToYamlFile($table, $exportFolder . $table . '.yml');
131
        }
132
    }
133
134
    // save permissions
135
    $skipColumns = [];
136
    $criteria = new \CriteriaCompo();
137
    $criteria->add(new \Criteria('gperm_modid', 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

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