Completed
Branch master (9259dd)
by
unknown
27:26
created

MwSql::execute()   F

Complexity

Conditions 21
Paths 4560

Size

Total Lines 97
Code Lines 65

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 21
eloc 65
nc 4560
nop 0
dl 0
loc 97
rs 2
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
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 32 and the first side effect is on line 25.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * Send SQL queries from the specified file to the database, performing
4
 * variable replacement along the way.
5
 *
6
 * This program is free software; you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation; either version 2 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License along
17
 * with this program; if not, write to the Free Software Foundation, Inc.,
18
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19
 * http://www.gnu.org/copyleft/gpl.html
20
 *
21
 * @file
22
 * @ingroup Maintenance
23
 */
24
25
require_once __DIR__ . '/Maintenance.php';
26
27
/**
28
 * Maintenance script that sends SQL queries from the specified file to the database.
29
 *
30
 * @ingroup Maintenance
31
 */
32
class MwSql extends Maintenance {
33
	public function __construct() {
34
		parent::__construct();
35
		$this->addDescription( 'Send SQL queries to a MediaWiki database. ' .
36
			'Takes a file name containing SQL as argument or runs interactively.' );
37
		$this->addOption( 'query', 'Run a single query instead of running interactively', false, true );
38
		$this->addOption( 'cluster', 'Use an external cluster by name', false, true );
39
		$this->addOption( 'wikidb', 'The database wiki ID to use if not the current one', false, true );
40
		$this->addOption( 'slave', 'Use a slave server (either "any" or by name)', false, true );
41
	}
42
43
	public function execute() {
0 ignored issues
show
Coding Style introduced by
execute uses the super-global variable $_ENV which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
44
		// We wan't to allow "" for the wikidb, meaning don't call select_db()
45
		$wiki = $this->hasOption( 'wikidb' ) ? $this->getOption( 'wikidb' ) : false;
46
		// Get the appropriate load balancer (for this wiki)
47
		if ( $this->hasOption( 'cluster' ) ) {
48
			$lb = wfGetLBFactory()->getExternalLB( $this->getOption( 'cluster' ), $wiki );
0 ignored issues
show
Deprecated Code introduced by
The function wfGetLBFactory() has been deprecated with message: since 1.27, use MediaWikiServices::getDBLoadBalancerFactory() instead.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
49
		} else {
50
			$lb = wfGetLB( $wiki );
0 ignored issues
show
Deprecated Code introduced by
The function wfGetLB() has been deprecated with message: since 1.27, use MediaWikiServices::getDBLoadBalancer() or MediaWikiServices::getDBLoadBalancerFactory() instead.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
51
		}
52
		// Figure out which server to use
53
		if ( $this->hasOption( 'slave' ) ) {
54
			$server = $this->getOption( 'slave' );
55
			if ( $server === 'any' ) {
56
				$index = DB_SLAVE;
57
			} else {
58
				$index = null;
59
				$serverCount = $lb->getServerCount();
60
				for ( $i = 0; $i < $serverCount; ++$i ) {
61
					if ( $lb->getServerName( $i ) === $server ) {
62
						$index = $i;
63
						break;
64
					}
65
				}
66
				if ( $index === null ) {
67
					$this->error( "No slave server configured with the name '$server'.", 1 );
68
				}
69
			}
70
		} else {
71
			$index = DB_MASTER;
72
		}
73
		// Get a DB handle (with this wiki's DB selected) from the appropriate load balancer
74
		$db = $lb->getConnection( $index, [], $wiki );
75
		if ( $this->hasOption( 'slave' ) && $db->getLBInfo( 'master' ) !== null ) {
76
			$this->error( "The server selected ({$db->getServer()}) is not a slave.", 1 );
77
		}
78
79
		if ( $this->hasArg( 0 ) ) {
80
			$file = fopen( $this->getArg( 0 ), 'r' );
81
			if ( !$file ) {
82
				$this->error( "Unable to open input file", true );
83
			}
84
85
			$error = $db->sourceStream( $file, false, [ $this, 'sqlPrintResult' ] );
86
			if ( $error !== true ) {
87
				$this->error( $error, true );
0 ignored issues
show
Bug introduced by
It seems like $error defined by $db->sourceStream($file,...his, 'sqlPrintResult')) on line 85 can also be of type boolean; however, Maintenance::error() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
88
			} else {
89
				exit( 0 );
0 ignored issues
show
Coding Style Compatibility introduced by
The method execute() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
90
			}
91
		}
92
93
		if ( $this->hasOption( 'query' ) ) {
94
			$query = $this->getOption( 'query' );
95
			$this->sqlDoQuery( $db, $query, /* dieOnError */ true );
96
			wfWaitForSlaves();
0 ignored issues
show
Deprecated Code introduced by
The function wfWaitForSlaves() has been deprecated with message: since 1.27 Use LBFactory::waitForReplication

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
97
			return;
98
		}
99
100
		$useReadline = function_exists( 'readline_add_history' )
101
			&& Maintenance::posix_isatty( 0 /*STDIN*/ );
102
103
		if ( $useReadline ) {
104
			global $IP;
105
			$historyFile = isset( $_ENV['HOME'] ) ?
106
				"{$_ENV['HOME']}/.mwsql_history" : "$IP/maintenance/.mwsql_history";
107
			readline_read_history( $historyFile );
108
		}
109
110
		$wholeLine = '';
111
		$newPrompt = '> ';
112
		$prompt = $newPrompt;
113
		$doDie = !Maintenance::posix_isatty( 0 );
114
		while ( ( $line = Maintenance::readconsole( $prompt ) ) !== false ) {
115
			if ( !$line ) {
116
				# User simply pressed return key
117
				continue;
118
			}
119
			$done = $db->streamStatementEnd( $wholeLine, $line );
120
121
			$wholeLine .= $line;
122
123
			if ( !$done ) {
124
				$wholeLine .= ' ';
125
				$prompt = '    -> ';
126
				continue;
127
			}
128
			if ( $useReadline ) {
129
				# Delimiter is eated by streamStatementEnd, we add it
130
				# up in the history (bug 37020)
131
				readline_add_history( $wholeLine . $db->getDelimiter() );
132
				readline_write_history( $historyFile );
0 ignored issues
show
Bug introduced by
The variable $historyFile does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
133
			}
134
			$this->sqlDoQuery( $db, $wholeLine, $doDie );
135
			$prompt = $newPrompt;
136
			$wholeLine = '';
137
		}
138
		wfWaitForSlaves();
0 ignored issues
show
Deprecated Code introduced by
The function wfWaitForSlaves() has been deprecated with message: since 1.27 Use LBFactory::waitForReplication

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
139
	}
140
141
	protected function sqlDoQuery( $db, $line, $dieOnError ) {
142
		try {
143
			$res = $db->query( $line );
144
			$this->sqlPrintResult( $res, $db );
145
		} catch ( DBQueryError $e ) {
146
			$this->error( $e, $dieOnError );
147
		}
148
	}
149
150
	/**
151
	 * Print the results, callback for $db->sourceStream()
152
	 * @param ResultWrapper $res The results object
153
	 * @param DatabaseBase $db
154
	 */
155
	public function sqlPrintResult( $res, $db ) {
156
		if ( !$res ) {
157
			// Do nothing
158
			return;
159
		} elseif ( is_object( $res ) && $res->numRows() ) {
160
			foreach ( $res as $row ) {
161
				$this->output( print_r( $row, true ) );
162
			}
163
		} else {
164
			$affected = $db->affectedRows();
165
			$this->output( "Query OK, $affected row(s) affected\n" );
166
		}
167
	}
168
169
	/**
170
	 * @return int DB_TYPE constant
171
	 */
172
	public function getDbType() {
173
		return Maintenance::DB_ADMIN;
174
	}
175
}
176
177
$maintClass = "MwSql";
178
require_once RUN_MAINTENANCE_IF_MAIN;
179