Completed
Branch master (5998bb)
by
unknown
29:17
created

CleanupEmptyCategories::doDBUpdates()   D

Complexity

Conditions 18
Paths 26

Size

Total Lines 123
Code Lines 74

Duplication

Lines 34
Ratio 27.64 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 18
eloc 74
nc 26
nop 0
dl 34
loc 123
rs 4.7996
c 1
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 24.

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
 * Clean up empty categories in the category table.
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
 */
23
24
require_once __DIR__ . '/Maintenance.php';
25
26
/**
27
 * Maintenance script to clean up empty categories in the category table.
28
 *
29
 * @ingroup Maintenance
30
 * @since 1.28
31
 */
32
class CleanupEmptyCategories extends LoggedUpdateMaintenance {
33
34 View Code Duplication
	public function __construct() {
35
		parent::__construct();
36
		$this->addDescription(
37
			<<<TEXT
38
This script will clean up the category table by removing entries for empty
39
categories without a description page and adding entries for empty categories
40
with a description page. It will print out progress indicators every batch. The
41
script is perfectly safe to run on large, live wikis, and running it multiple
42
times is harmless. You may want to use the throttling options if it's causing
43
too much load; they will not affect correctness.
44
45
If the script is stopped and later resumed, you can use the --mode and --begin
46
options with the last printed progress indicator to pick up where you left off.
47
48
When the script has finished, it will make a note of this in the database, and
49
will not run again without the --force option.
50
TEXT
51
		);
52
53
		$this->addOption(
54
			'mode',
55
			'"add" empty categories with description pages, "remove" empty categories '
56
			. 'without description pages, or "both"',
57
			false,
58
			true
59
		);
60
		$this->addOption(
61
			'begin',
62
			'Only do categories whose names are alphabetically after the provided name',
63
			false,
64
			true
65
		);
66
		$this->addOption(
67
			'throttle',
68
			'Wait this many milliseconds after each batch. Default: 0',
69
			false,
70
			true
71
		);
72
	}
73
74
	protected function getUpdateKey() {
75
		return 'cleanup empty categories';
76
	}
77
78
	protected function doDBUpdates() {
79
		$mode = $this->getOption( 'mode', 'both' );
80
		$begin = $this->getOption( 'begin', '' );
81
		$throttle = $this->getOption( 'throttle', 0 );
82
83
		if ( !in_array( $mode, [ 'add', 'remove', 'both' ] ) ) {
84
			$this->output( "--mode must be 'add', 'remove', or 'both'.\n" );
85
			return false;
86
		}
87
88
		$dbw = $this->getDB( DB_MASTER );
89
90
		$throttle = intval( $throttle );
91
92
		if ( $mode === 'add' || $mode === 'both' ) {
93 View Code Duplication
			if ( $begin !== '' ) {
94
				$where = [ 'page_title > ' . $dbw->addQuotes( $begin ) ];
95
			} else {
96
				$where = [];
97
			}
98
99
			$this->output( "Adding empty categories with description pages...\n" );
100
			while ( true ) {
101
				# Find which category to update
102
				$rows = $dbw->select(
103
					[ 'page', 'category' ],
104
					'page_title',
105
					array_merge( $where, [
106
						'page_namespace' => NS_CATEGORY,
107
						'cat_title' => null,
108
					] ),
109
					__METHOD__,
110
					[
111
						'ORDER BY' => 'page_title',
112
						'LIMIT' => $this->mBatchSize,
113
					],
114
					[
115
						'category' => [ 'LEFT JOIN', 'page_title = cat_title' ],
116
					]
117
				);
118
				if ( !$rows || $rows->numRows() <= 0 ) {
119
					# Done, hopefully.
120
					break;
121
				}
122
123 View Code Duplication
				foreach ( $rows as $row ) {
0 ignored issues
show
Bug introduced by
The expression $rows of type object<ResultWrapper>|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
124
					$name = $row->page_title;
125
					$where = [ 'page_title > ' . $dbw->addQuotes( $name ) ];
126
127
					# Use the row to update the category count
128
					$cat = Category::newFromName( $name );
129
					if ( !is_object( $cat ) ) {
130
						$this->output( "The category named $name is not valid?!\n" );
131
					} else {
132
						$cat->refreshCounts();
133
					}
134
				}
135
				$this->output( "--mode=$mode --begin=$name\n" );
0 ignored issues
show
Bug introduced by
The variable $name 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...
136
137
				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...
138
				usleep( $throttle * 1000 );
139
			}
140
141
			$begin = '';
142
		}
143
144
		if ( $mode === 'remove' || $mode === 'both' ) {
145 View Code Duplication
			if ( $begin !== '' ) {
146
				$where = [ 'cat_title > ' . $dbw->addQuotes( $begin ) ];
147
			} else {
148
				$where = [];
149
			}
150
			$i = 0;
0 ignored issues
show
Unused Code introduced by
$i is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
151
152
			$this->output( "Removing empty categories without description pages...\n" );
153
			while ( true ) {
154
				# Find which category to update
155
				$rows = $dbw->select(
156
					[ 'category', 'page' ],
157
					'cat_title',
158
					array_merge( $where, [
159
						'page_title' => null,
160
						'cat_pages' => 0,
161
					] ),
162
					__METHOD__,
163
					[
164
						'ORDER BY' => 'cat_title',
165
						'LIMIT' => $this->mBatchSize,
166
					],
167
					[
168
						'page' => [ 'LEFT JOIN', [
169
							'page_namespace' => NS_CATEGORY, 'page_title = cat_title'
170
						] ],
171
					]
172
				);
173
				if ( !$rows || $rows->numRows() <= 0 ) {
174
					# Done, hopefully.
175
					break;
176
				}
177 View Code Duplication
				foreach ( $rows as $row ) {
0 ignored issues
show
Bug introduced by
The expression $rows of type object<ResultWrapper>|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
178
					$name = $row->cat_title;
179
					$where = [ 'cat_title > ' . $dbw->addQuotes( $name ) ];
180
181
					# Use the row to update the category count
182
					$cat = Category::newFromName( $name );
183
					if ( !is_object( $cat ) ) {
184
						$this->output( "The category named $name is not valid?!\n" );
185
					} else {
186
						$cat->refreshCounts();
187
					}
188
				}
189
190
				$this->output( "--mode=remove --begin=$name\n" );
191
192
				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...
193
				usleep( $throttle * 1000 );
194
			}
195
		}
196
197
		$this->output( "Category cleanup complete.\n" );
198
199
		return true;
200
	}
201
}
202
203
$maintClass = 'CleanupEmptyCategories';
204
require_once RUN_MAINTENANCE_IF_MAIN;
205