exportSchema()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 13
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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

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