Passed
Pull Request — develop (#92)
by Felipe
04:25
created

SqlController   B

Complexity

Total Complexity 49

Size/Duplication

Total Lines 323
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 323
rs 8.5454
c 0
b 0
f 0
wmc 49

5 Methods

Rating   Name   Duplication   Size   Complexity  
B doDefault() 0 22 4
C doFooter() 0 95 11
B execute_query() 0 55 9
C render() 0 64 14
C execute_script() 0 65 11

How to fix   Complexity   

Complex Class

Complex classes like SqlController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use SqlController, and based on these observations, apply Extract Interface, too.

1
<?php
2
0 ignored issues
show
Coding Style introduced by
You must use "/**" style comments for a file comment
Loading history...
3
/*
4
 * PHPPgAdmin v6.0.0-beta.30
5
 */
6
7
namespace PHPPgAdmin\Controller;
8
9
/**
10
 * Base controller class.
11
 */
5 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @package tag in class comment
Loading history...
Coding Style introduced by
Missing @author tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
12
class SqlController extends BaseController
13
{
14
    public $controller_name = 'SqlController';
15
    public $query           = '';
16
    public $subject         = '';
17
    public $start_time;
18
    public $duration;
19
20
    /**
21
     * Default method to render the controller according to the action parameter.
22
     */
23
    public function render()
24
    {
25
        $lang = $this->lang;
26
27
        $data = $this->misc->getDatabaseAccessor();
28
29
        set_time_limit(0);
30
31
        // We need to store the query in a session for editing purposes
32
        // We avoid GPC vars to avoid truncating long queries
33
        if (isset($_REQUEST['subject']) && 'history' == $_REQUEST['subject']) {
34
            // Or maybe we came from the history popup
35
            $_SESSION['sqlquery'] = $_SESSION['history'][$_REQUEST['server']][$_REQUEST['database']][$_GET['queryid']]['query'];
36
            $this->query          = $_SESSION['sqlquery'];
37
        } elseif (isset($_POST['query'])) {
38
            // Or maybe we came from an sql form
39
            $_SESSION['sqlquery'] = $_POST['query'];
40
            $this->query          = $_SESSION['sqlquery'];
41
        } else {
42
            echo 'could not find the query!!';
43
        }
44
45
        // Pagination maybe set by a get link that has it as FALSE,
46
        // if that's the case, unset the variable.
47
        if (isset($_REQUEST['paginate']) && 'f' == $_REQUEST['paginate']) {
48
            unset($_REQUEST['paginate'], $_POST['paginate'], $_GET['paginate']);
49
        }
50
51
        if (isset($_REQUEST['subject'])) {
52
            $this->subject = $_REQUEST['subject'];
53
        }
54
55
        // Check to see if pagination has been specified. In that case, send to display
56
        // script for pagination
57
        // if a file is given or the request is an explain, do not paginate
58
        if (isset($_REQUEST['paginate']) && !(isset($_FILES['script']) && $_FILES['script']['size'] > 0) && (0 == preg_match('/^\s*explain/i', $this->query))) {
59
            //if (!(isset($_FILES['script']) && $_FILES['script']['size'] > 0)) {
60
61
            $display_controller = new DisplayController($this->getContainer());
62
63
            return $display_controller->render();
64
        }
65
66
        $this->printHeader($lang['strqueryresults'], null, true, 'header_sqledit.twig');
67
        $this->printBody();
68
        $this->printTrail('database');
69
        $this->printTitle($lang['strqueryresults']);
70
71
        // Set the schema search path
72
        if (isset($_REQUEST['search_path'])) {
73
            if (0 != $data->setSearchPath(array_map('trim', explode(',', $_REQUEST['search_path'])))) {
74
                return $this->printFooter();
75
            }
76
        }
77
78
        // May as well try to time the query
79
        if (function_exists('microtime')) {
80
            list($usec, $sec) = explode(' ', microtime());
81
            $this->start_time = ((float) $usec + (float) $sec);
82
        }
83
84
        $this->doDefault();
85
86
        $this->doFooter(true, 'footer_sqledit.twig');
87
    }
88
89
    public function doDefault()
1 ignored issue
show
Coding Style introduced by
Missing function doc comment
Loading history...
90
    {
91
        $conf        = $this->conf;
0 ignored issues
show
Unused Code introduced by
The assignment to $conf is dead and can be removed.
Loading history...
92
        $this->misc  = $this->misc;
93
        $lang        = $this->lang;
0 ignored issues
show
Unused Code introduced by
The assignment to $lang is dead and can be removed.
Loading history...
94
        $data        = $this->misc->getDatabaseAccessor();
0 ignored issues
show
Unused Code introduced by
The assignment to $data is dead and can be removed.
Loading history...
95
        $_connection = $this->misc->getConnection();
96
97
        try {
98
            // Execute the query.  If it's a script upload, special handling is necessary
99
            if (isset($_FILES['script']) && $_FILES['script']['size'] > 0) {
100
                return $this->execute_script();
101
            }
102
103
            return $this->execute_query();
104
        } catch (\PHPPgAdmin\ADOdbException $e) {
105
            $message   = $e->getMessage();
106
            $trace     = $e->getTraceAsString();
107
            $lastError = $_connection->getLastError();
108
            $this->prtrace(['message' => $message, 'trace' => $trace, 'lastError' => $lastError]);
109
110
            return null;
111
        }
112
    }
113
114
    private function execute_script()
2 ignored issues
show
Coding Style introduced by
Private method name "SqlController::execute_script" must be prefixed with an underscore
Loading history...
Coding Style introduced by
Missing function doc comment
Loading history...
115
    {
116
        $conf        = $this->conf;
0 ignored issues
show
Unused Code introduced by
The assignment to $conf is dead and can be removed.
Loading history...
117
        $misc        = $this->misc;
118
        $lang        = $this->lang;
119
        $data        = $this->misc->getDatabaseAccessor();
120
        $_connection = $this->misc->getConnection();
121
122
        /**
123
         * This is a callback function to display the result of each separate query.
124
         *
125
         * @param ADORecordSet $rs The recordset returned by the script execetor
126
         */
127
        $sqlCallback = function ($query, $rs, $lineno) use ($data, $misc, $lang, $_connection) {
128
            // Check if $rs is false, if so then there was a fatal error
129
            if (false === $rs) {
130
                echo htmlspecialchars($_FILES['script']['name']), ':', $lineno, ': ', nl2br(htmlspecialchars($_connection->getLastError())), "<br/>\n";
131
            } else {
132
                // Print query results
133
                switch (pg_result_status($rs)) {
134
                    case PGSQL_TUPLES_OK:
135
                        // If rows returned, then display the results
136
                        $num_fields = pg_numfields($rs);
137
                        echo "<p><table>\n<tr>";
138
                        for ($k = 0; $k < $num_fields; ++$k) {
139
                            echo '<th class="data">', $misc->printVal(pg_fieldname($rs, $k)), '</th>';
140
                        }
141
142
                        $i   = 0;
143
                        $row = pg_fetch_row($rs);
144
                        while (false !== $row) {
145
                            $id = (0 == ($i % 2) ? '1' : '2');
146
                            echo "<tr class=\"data{$id}\">\n";
147
                            foreach ($row as $k => $v) {
148
                                echo '<td style="white-space:nowrap;">', $misc->printVal($v, pg_fieldtype($rs, $k), ['null' => true]), '</td>';
149
                            }
150
                            echo "</tr>\n";
151
                            $row = pg_fetch_row($rs);
152
                            ++$i;
153
                        }
154
155
                        echo "</table><br/>\n";
156
                        echo $i, " {$lang['strrows']}</p>\n";
157
158
                        break;
159
                    case PGSQL_COMMAND_OK:
160
                        // If we have the command completion tag
161
                        if (version_compare(phpversion(), '4.3', '>=')) {
162
                            echo htmlspecialchars(pg_result_status($rs, PGSQL_STATUS_STRING)), "<br/>\n";
163
                        }
164
                        // Otherwise if any rows have been affected
165
                        elseif ($data->conn->Affected_Rows() > 0) {
0 ignored issues
show
Coding Style introduced by
Expected "} elseif (...) \n"; found "\n // Otherwise if any rows have been affected\n elseif (...) {\n"
Loading history...
166
                            echo $data->conn->Affected_Rows(), " {$lang['strrowsaff']}<br/>\n";
167
                        }
168
                        // Otherwise output nothing...
169
                        break;
170
                    case PGSQL_EMPTY_QUERY:
171
                        break;
172
                    default:
173
                        break;
174
                }
175
            }
176
        };
177
178
        return $data->executeScript('script', $sqlCallback);
179
    }
180
181
    private function execute_query()
2 ignored issues
show
Coding Style introduced by
Private method name "SqlController::execute_query" must be prefixed with an underscore
Loading history...
Coding Style introduced by
Missing function doc comment
Loading history...
182
    {
183
        $lang = $this->lang;
184
        $data = $this->misc->getDatabaseAccessor();
185
186
        // Set fetch mode to NUM so that duplicate field names are properly returned
187
        $data->conn->setFetchMode(ADODB_FETCH_NUM);
188
189
        $rs = $data->conn->Execute($this->query);
190
191
        echo '<form method="post" id="sqlform" action="' . $_SERVER['REQUEST_URI'] . '">';
192
        echo '<textarea width="90%" name="query"  id="query" rows="5" cols="100" resizable="true">';
193
194
        echo htmlspecialchars($this->query);
195
        echo '</textarea><br>';
196
        echo $this->misc->setForm();
197
        echo '<input type="submit"/></form>';
198
199
        // $rs will only be an object if there is no error
200
        if (is_object($rs)) {
201
            // Request was run, saving it in history
202
            if (!isset($_REQUEST['nohistory'])) {
203
                $this->misc->saveScriptHistory($this->query);
204
            }
205
206
            // Now, depending on what happened do various things
207
208
            // First, if rows returned, then display the results
209
            if ($rs->recordCount() > 0) {
210
                echo "<table>\n<tr>";
211
                foreach ($rs->fields as $k => $v) {
212
                    $finfo = $rs->fetchField($k);
213
                    echo '<th class="data">', $this->misc->printVal($finfo->name), '</th>';
214
                }
215
                echo "</tr>\n";
216
                $i = 0;
217
                while (!$rs->EOF) {
218
                    $id = (0 == ($i % 2) ? '1' : '2');
219
                    echo "<tr class=\"data{$id}\">\n";
220
                    foreach ($rs->fields as $k => $v) {
221
                        $finfo = $rs->fetchField($k);
222
                        echo '<td style="white-space:nowrap;">', $this->misc->printVal($v, $finfo->type, ['null' => true]), '</td>';
223
                    }
224
                    echo "</tr>\n";
225
                    $rs->moveNext();
226
                    ++$i;
227
                }
228
                echo "</table>\n";
229
                echo '<p>', $rs->recordCount(), " {$lang['strrows']}</p>\n";
230
            } elseif ($data->conn->Affected_Rows() > 0) {
231
                // Otherwise if any rows have been affected
232
                echo '<p>', $data->conn->Affected_Rows(), " {$lang['strrowsaff']}</p>\n";
233
            } else {
234
                // Otherwise nodata to print
235
                echo '<p>', $lang['strnodata'], "</p>\n";
236
            }
237
        }
238
    }
239
240
    private function doFooter($doBody = true, $template = 'footer.twig')
2 ignored issues
show
Coding Style introduced by
Private method name "SqlController::doFooter" must be prefixed with an underscore
Loading history...
Coding Style introduced by
Missing function doc comment
Loading history...
241
    {
242
        $lang = $this->lang;
243
        $data = $this->misc->getDatabaseAccessor();
244
245
        // May as well try to time the query
246
        if (null !== $this->start_time) {
247
            list($usec, $sec) = explode(' ', microtime());
248
            $end_time         = ((float) $usec + (float) $sec);
249
            // Get duration in milliseconds, round to 3dp's
250
            $this->duration = number_format(($end_time - $this->start_time) * 1000, 3);
251
        }
252
253
        // Reload the browser as we may have made schema changes
254
        $this->misc->setReloadBrowser(true);
255
256
        // Display duration if we know it
257
        if (null !== $this->duration) {
258
            echo '<p>', sprintf($lang['strruntime'], $this->duration), "</p>\n";
259
        }
260
261
        echo "<p>{$lang['strsqlexecuted']}</p>\n";
262
263
        $navlinks = [];
264
        $fields   = [
265
            'server'   => $_REQUEST['server'],
266
            'database' => $_REQUEST['database'],
267
        ];
268
269
        if (isset($_REQUEST['schema'])) {
270
            $fields['schema'] = $_REQUEST['schema'];
271
        }
272
273
        // Return
274
        if (isset($_REQUEST['return'])) {
275
            $urlvars          = $this->misc->getSubjectParams($_REQUEST['return']);
276
            $navlinks['back'] = [
277
                'attr'    => [
278
                    'href' => [
279
                        'url'     => $urlvars['url'],
280
                        'urlvars' => $urlvars['params'],
281
                    ],
282
                ],
283
                'content' => $lang['strback'],
284
            ];
285
        }
286
287
        // Edit
288
        $navlinks['alter'] = [
289
            'attr'    => [
290
                'href' => [
291
                    'url'     => 'database.php',
292
                    'urlvars' => array_merge($fields, [
1 ignored issue
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
293
                        'action' => 'sql',
294
                    ]),
1 ignored issue
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
295
                ],
296
            ],
297
            'content' => $lang['streditsql'],
298
        ];
299
300
        // Create view and download
301
        if ('' !== $this->query && isset($rs) && is_object($rs) && $rs->recordCount() > 0) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $rs seems to never exist and therefore isset should always be false.
Loading history...
302
            // Report views don't set a schema, so we need to disable create view in that case
303
            if (isset($_REQUEST['schema'])) {
304
                $navlinks['createview'] = [
305
                    'attr'    => [
306
                        'href' => [
307
                            'url'     => 'views.php',
308
                            'urlvars' => array_merge($fields, [
1 ignored issue
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
309
                                'action' => 'create',
310
                            ]),
1 ignored issue
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
311
                        ],
312
                    ],
313
                    'content' => $lang['strcreateview'],
314
                ];
315
            }
316
317
            if (isset($_REQUEST['search_path'])) {
318
                $fields['search_path'] = $_REQUEST['search_path'];
319
            }
320
321
            $navlinks['download'] = [
322
                'attr'    => [
323
                    'href' => [
324
                        'url'     => 'dataexport.php',
325
                        'urlvars' => $fields,
326
                    ],
327
                ],
328
                'content' => $lang['strdownload'],
329
            ];
330
        }
331
332
        $this->printNavLinks($navlinks, 'sql-form', get_defined_vars());
333
334
        return $this->printFooter($doBody, $template);
335
    }
336
}
337