MysqlDumper::createDump()   F
last analyzed

Complexity

Conditions 18
Paths 2592

Size

Total Lines 111

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 18
nc 2592
nop 1
dl 0
loc 111
rs 0.56
c 0
b 0
f 0

How to fix   Long Method    Complexity   

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 namespace EvolutionCMS\Support;
2
3
use EvolutionCMS\Interfaces\MysqlDumperInterface;
4
5
/**
6
 * @package  MySQLdumper
7
 * @version  1.0
8
 * @author   Dennis Mozes <[email protected]>
9
 * @url        http://www.mosix.nl/mysqldumper
10
 * @since    PHP 4.0
11
 * @copyright Dennis Mozes
12
 * @license GNU/LGPL License: http://www.gnu.org/copyleft/lgpl.html
13
 *
14
 * Modified by Raymond for use with this module
15
 *
16
 **/
17
class MysqlDumper implements MysqlDumperInterface
18
{
19
    /**
20
     * @var array
21
     */
22
    public $_dbtables;
23
    /**
24
     * @var bool
25
     */
26
    public $_isDroptables;
27
    /**
28
     * @var string
29
     */
30
    public $dbname;
31
    /**
32
     * @var string
33
     */
34
    public $database_server;
35
36
    /**
37
     * Mysqldumper constructor.
38
     * @param string $dbname
39
     */
40
    public function __construct($dbname)
41
    {
42
        // Don't drop tables by default.
43
        $this->dbname = $dbname;
44
        $this->setDroptables(false);
45
    }
46
47
    /**
48
     * If set to true, it will generate 'DROP TABLE IF EXISTS'-statements for each table.
49
     *
50
     * @param bool $state
51
     */
52
    public function setDroptables($state)
53
    {
54
        $this->_isDroptables = $state;
55
    }
56
57
    /**
58
     * @param array $dbtables
59
     */
60
    public function setDBtables($dbtables)
61
    {
62
        $this->_dbtables = $dbtables;
63
    }
64
65
    /**
66
     * @param string $callBack
67
     * @return bool
68
     */
69
    public function createDump($callBack)
70
    {
71
        $modx = evolutionCMS();
72
        $createtable = array();
73
74
        // Set line feed
75
        $lf = "\n";
76
        $tempfile_path = MODX_BASE_PATH . 'assets/backup/temp.php';
77
78
        $result = $modx->getDatabase()->query('SHOW TABLES');
79
        $tables = $this->result2Array(0, $result);
80
        foreach ($tables as $tblval) {
81
            $result = $modx->getDatabase()->query("SHOW CREATE TABLE `{$tblval}`");
82
            $createtable[$tblval] = $this->result2Array(1, $result);
83
        }
84
85
        $version = $modx->getVersionData();
86
87
        // Set header
88
        $output = "#{$lf}";
89
        $output .= "# " . addslashes($modx->getPhpCompat()->entities($modx->getConfig('site_name'))) . " Database Dump{$lf}";
90
        $output .= "# Evolution CMS Version:{$version['version']}{$lf}";
91
        $output .= "# {$lf}";
92
        $output .= "# Host: {$this->database_server}{$lf}";
93
        $output .= "# Generation Time: " . $modx->toDateFormat(time()) . $lf;
94
        $output .= "# Server version: " . $modx->getDatabase()->getVersion() . $lf;
95
        $output .= "# PHP Version: " . phpversion() . $lf;
96
        $output .= "# Database: `{$this->dbname}`{$lf}";
97
        $output .= "# Description: " . trim($_REQUEST['backup_title']) . "{$lf}";
98
        $output .= "#";
99
        file_put_contents($tempfile_path, $output, FILE_APPEND | LOCK_EX);
100
        $output = '';
101
102
        // Generate dumptext for the tables.
103
        if (isset($this->_dbtables) && count($this->_dbtables)) {
104
            $this->_dbtables = implode(',', $this->_dbtables);
0 ignored issues
show
Documentation Bug introduced by
It seems like implode(',', $this->_dbtables) of type string is incompatible with the declared type array of property $_dbtables.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
105
        } else {
106
            unset($this->_dbtables);
107
        }
108
        foreach ($tables as $tblval) {
109
            // check for selected table
110
            if (isset($this->_dbtables)) {
111
                if (strstr(",{$this->_dbtables},", ",{$tblval},") === false) {
112
                    continue;
113
                }
114
            }
115
            if ($callBack === 'snapshot') {
116
                if (!preg_match('@^' . $modx->getDatabase()->getConfig('prefix') . '@', $tblval)) {
117
                    continue;
118
                }
119
            }
120
            $output .= "{$lf}{$lf}# --------------------------------------------------------{$lf}{$lf}";
121
            $output .= "#{$lf}# Table structure for table `{$tblval}`{$lf}";
122
            $output .= "#{$lf}{$lf}";
123
            // Generate DROP TABLE statement when client wants it to.
124
            if ($this->isDroptables()) {
125
                $output .= "SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;{$lf}";
126
                $output .= "DROP TABLE IF EXISTS `{$tblval}`;{$lf}";
127
                $output .= "SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;{$lf}{$lf}";
128
            }
129
            $output .= "{$createtable[$tblval][0]};{$lf}";
130
            $output .= $lf;
131
            $output .= "#{$lf}# Dumping data for table `{$tblval}`{$lf}#{$lf}";
132
            $result = $modx->getDatabase()->select('*', $tblval);
133
            $rows = $this->loadObjectList('', $result);
134
            foreach ($rows as $row) {
135
                $insertdump = $lf;
136
                $insertdump .= "INSERT INTO `{$tblval}` VALUES (";
137
                $arr = $this->object2Array($row);
138
                if (!is_array($arr)) {
139
                    $arr = array();
140
                }
141
                foreach ($arr as $key => $value) {
142
                    if (is_null($value)) {
143
                        $value = 'NULL';
144
                    } else {
145
                        $value = addslashes($value);
146
                        $value = str_replace(array(
147
                            "\r\n",
148
                            "\r",
149
                            "\n"
150
                        ), '\\n', $value);
151
                        $value = "'{$value}'";
152
                    }
153
                    $insertdump .= $value . ',';
154
                }
155
                $output .= rtrim($insertdump, ',') . ");\n";
156
                if (1048576 < strlen($output)) {
157
                    file_put_contents($tempfile_path, $output, FILE_APPEND | LOCK_EX);
158
                    $output = '';
159
                }
160
            }
161
            file_put_contents($tempfile_path, $output, FILE_APPEND | LOCK_EX);
162
            $output = '';
163
        }
164
        $output = file_get_contents($tempfile_path);
165
        if (!empty($output)) {
166
            unlink($tempfile_path);
167
        }
168
169
        switch ($callBack) {
170
            case 'dumpSql':
171
                dumpSql($output);
172
                break;
173
            case 'snapshot':
174
                snapshot($output);
175
                break;
176
        }
177
178
        return true;
179
    }
180
181
    /**
182
     * @param int $numinarray
183
     * @param \mysqli_result $resource
184
     * @return array
185
     */
186
    public function result2Array($numinarray = 0, $resource)
187
    {
188
        $modx = evolutionCMS();
189
        $array = array();
190
        while ($row = $modx->getDatabase()->getRow($resource, 'num')) {
191
            $array[] = $row[$numinarray];
192
        }
193
194
        return $array;
195
    }
196
197
    /**
198
     * @return bool
199
     */
200
    public function isDroptables()
201
    {
202
        return $this->_isDroptables;
203
    }
204
205
    /**
206
     * @param string $key
207
     * @param \mysqli_result $resource
208
     * @return array
209
     */
210
    public function loadObjectList($key = '', $resource)
211
    {
212
        $modx = evolutionCMS();
213
        $array = array();
214
        while ($row = $modx->getDatabase()->getRow($resource, 'object')) {
215
            if ($key) {
216
                $array[$row->$key] = $row;
217
            } else {
218
                $array[] = $row;
219
            }
220
        }
221
222
        return $array;
223
    }
224
225
    /**
226
     * @param \stdClass $obj
227
     * @return array|null
228
     */
229
    public function object2Array($obj)
230
    {
231
        $array = null;
232
        if (is_object($obj)) {
233
            $array = array();
234
            foreach (get_object_vars($obj) as $key => $value) {
235
                if (is_object($value)) {
236
                    $array[$key] = $this->object2Array($value);
237
                } else {
238
                    $array[$key] = $value;
239
                }
240
            }
241
        }
242
243
        return $array;
244
    }
245
}
246