ReassignEdits::doReassignEdits()   B
last analyzed

Complexity

Conditions 5
Paths 8

Size

Total Lines 70
Code Lines 51

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 51
nc 8
nop 4
dl 0
loc 70
rs 8.5454
c 0
b 0
f 0

How to fix   Long Method   

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 34 and the first side effect is on line 26.

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
 * Reassign edits from a user or IP address to another user
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation; either version 2 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License along
16
 * with this program; if not, write to the Free Software Foundation, Inc.,
17
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18
 * http://www.gnu.org/copyleft/gpl.html
19
 *
20
 * @file
21
 * @ingroup Maintenance
22
 * @author Rob Church <[email protected]>
23
 * @licence GNU General Public Licence 2.0 or later
24
 */
25
26
require_once __DIR__ . '/Maintenance.php';
27
28
/**
29
 * Maintenance script that reassigns edits from a user or IP address
30
 * to another user.
31
 *
32
 * @ingroup Maintenance
33
 */
34
class ReassignEdits extends Maintenance {
35
	public function __construct() {
36
		parent::__construct();
37
		$this->addDescription( 'Reassign edits from one user to another' );
38
		$this->addOption( "force", "Reassign even if the target user doesn't exist" );
39
		$this->addOption( "norc", "Don't update the recent changes table" );
40
		$this->addOption( "report", "Print out details of what would be changed, but don't update it" );
41
		$this->addArg( 'from', 'Old user to take edits from' );
42
		$this->addArg( 'to', 'New user to give edits to' );
43
	}
44
45
	public function execute() {
46
		if ( $this->hasArg( 0 ) && $this->hasArg( 1 ) ) {
47
			# Set up the users involved
48
			$from = $this->initialiseUser( $this->getArg( 0 ) );
49
			$to = $this->initialiseUser( $this->getArg( 1 ) );
50
51
			# If the target doesn't exist, and --force is not set, stop here
52
			if ( $to->getId() || $this->hasOption( 'force' ) ) {
53
				# Reassign the edits
54
				$report = $this->hasOption( 'report' );
55
				$this->doReassignEdits( $from, $to, !$this->hasOption( 'norc' ), $report );
56
				# If reporting, and there were items, advise the user to run without --report
57
				if ( $report ) {
58
					$this->output( "Run the script again without --report to update.\n" );
59
				}
60
			} else {
61
				$ton = $to->getName();
62
				$this->error( "User '{$ton}' not found." );
63
			}
64
		}
65
	}
66
67
	/**
68
	 * Reassign edits from one user to another
69
	 *
70
	 * @param User $from User to take edits from
71
	 * @param User $to User to assign edits to
72
	 * @param bool $rc Update the recent changes table
73
	 * @param bool $report Don't change things; just echo numbers
74
	 * @return int Number of entries changed, or that would be changed
75
	 */
76
	private function doReassignEdits( &$from, &$to, $rc = false, $report = false ) {
77
		$dbw = $this->getDB( DB_MASTER );
78
		$this->beginTransaction( $dbw, __METHOD__ );
0 ignored issues
show
Bug introduced by
It seems like $dbw defined by $this->getDB(DB_MASTER) on line 77 can be null; however, Maintenance::beginTransaction() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
79
80
		# Count things
81
		$this->output( "Checking current edits..." );
82
		$res = $dbw->select(
83
			'revision',
84
			'COUNT(*) AS count',
85
			$this->userConditions( $from, 'rev_user', 'rev_user_text' ),
86
			__METHOD__
87
		);
88
		$row = $dbw->fetchObject( $res );
89
		$cur = $row->count;
90
		$this->output( "found {$cur}.\n" );
91
92
		$this->output( "Checking deleted edits..." );
93
		$res = $dbw->select(
94
			'archive',
95
			'COUNT(*) AS count',
96
			$this->userConditions( $from, 'ar_user', 'ar_user_text' ),
97
			__METHOD__
98
		);
99
		$row = $dbw->fetchObject( $res );
100
		$del = $row->count;
101
		$this->output( "found {$del}.\n" );
102
103
		# Don't count recent changes if we're not supposed to
104
		if ( $rc ) {
105
			$this->output( "Checking recent changes..." );
106
			$res = $dbw->select(
107
				'recentchanges',
108
				'COUNT(*) AS count',
109
				$this->userConditions( $from, 'rc_user', 'rc_user_text' ),
110
				__METHOD__
111
			);
112
			$row = $dbw->fetchObject( $res );
113
			$rec = $row->count;
114
			$this->output( "found {$rec}.\n" );
115
		} else {
116
			$rec = 0;
117
		}
118
119
		$total = $cur + $del + $rec;
120
		$this->output( "\nTotal entries to change: {$total}\n" );
121
122
		if ( !$report ) {
123
			if ( $total ) {
124
				# Reassign edits
125
				$this->output( "\nReassigning current edits..." );
126
				$dbw->update( 'revision', $this->userSpecification( $to, 'rev_user', 'rev_user_text' ),
127
					$this->userConditions( $from, 'rev_user', 'rev_user_text' ), __METHOD__ );
128
				$this->output( "done.\nReassigning deleted edits..." );
129
				$dbw->update( 'archive', $this->userSpecification( $to, 'ar_user', 'ar_user_text' ),
130
					$this->userConditions( $from, 'ar_user', 'ar_user_text' ), __METHOD__ );
131
				$this->output( "done.\n" );
132
				# Update recent changes if required
133
				if ( $rc ) {
134
					$this->output( "Updating recent changes..." );
135
					$dbw->update( 'recentchanges', $this->userSpecification( $to, 'rc_user', 'rc_user_text' ),
136
						$this->userConditions( $from, 'rc_user', 'rc_user_text' ), __METHOD__ );
137
					$this->output( "done.\n" );
138
				}
139
			}
140
		}
141
142
		$this->commitTransaction( $dbw, __METHOD__ );
0 ignored issues
show
Bug introduced by
It seems like $dbw defined by $this->getDB(DB_MASTER) on line 77 can be null; however, Maintenance::commitTransaction() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
143
144
		return (int)$total;
145
	}
146
147
	/**
148
	 * Return the most efficient set of user conditions
149
	 * i.e. a user => id mapping, or a user_text => text mapping
150
	 *
151
	 * @param User $user User for the condition
152
	 * @param string $idfield Field name containing the identifier
153
	 * @param string $utfield Field name containing the user text
154
	 * @return array
155
	 */
156
	private function userConditions( &$user, $idfield, $utfield ) {
157
		return $user->getId()
158
			? [ $idfield => $user->getId() ]
159
			: [ $utfield => $user->getName() ];
160
	}
161
162
	/**
163
	 * Return user specifications
164
	 * i.e. user => id, user_text => text
165
	 *
166
	 * @param User $user User for the spec
167
	 * @param string $idfield Field name containing the identifier
168
	 * @param string $utfield Field name containing the user text
169
	 * @return array
170
	 */
171
	private function userSpecification( &$user, $idfield, $utfield ) {
172
		return [ $idfield => $user->getId(), $utfield => $user->getName() ];
173
	}
174
175
	/**
176
	 * Initialise the user object
177
	 *
178
	 * @param string $username Username or IP address
179
	 * @return User
180
	 */
181
	private function initialiseUser( $username ) {
182
		if ( User::isIP( $username ) ) {
183
			$user = new User();
184
			$user->setId( 0 );
185
			$user->setName( $username );
186
		} else {
187
			$user = User::newFromName( $username );
188
			if ( !$user ) {
189
				$this->error( "Invalid username", true );
190
			}
191
		}
192
		$user->load();
193
194
		return $user;
195
	}
196
}
197
198
$maintClass = "ReassignEdits";
199
require_once RUN_MAINTENANCE_IF_MAIN;
200