ImportSiteScripts   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 84
Duplicated Lines 5.95 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
dl 5
loc 84
rs 10
c 0
b 0
f 0
wmc 12
lcom 1
cbo 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
B execute() 5 33 4
C fetchScriptList() 0 40 7

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
 * Import all scripts in the MediaWiki namespace from a local site.
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 import all scripts in the MediaWiki namespace from a
28
 * local site.
29
 *
30
 * @ingroup Maintenance
31
 */
32
class ImportSiteScripts extends Maintenance {
33
	public function __construct() {
34
		parent::__construct();
35
		$this->addDescription( 'Import site scripts from a site' );
36
		$this->addArg( 'api', 'API base url' );
37
		$this->addArg( 'index', 'index.php base url' );
38
		$this->addOption( 'username', 'User name of the script importer' );
39
	}
40
41
	public function execute() {
42
		global $wgUser;
43
44
		$username = $this->getOption( 'username', false );
45 View Code Duplication
		if ( $username === false ) {
46
			$user = User::newSystemUser( 'ScriptImporter', [ 'steal' => true ] );
47
		} else {
48
			$user = User::newFromName( $username );
49
		}
50
		$wgUser = $user;
51
52
		$baseUrl = $this->getArg( 1 );
53
		$pageList = $this->fetchScriptList();
54
		$this->output( 'Importing ' . count( $pageList ) . " pages\n" );
55
56
		foreach ( $pageList as $page ) {
57
			$title = Title::makeTitleSafe( NS_MEDIAWIKI, $page );
58
			if ( !$title ) {
59
				$this->error( "$page is an invalid title; it will not be imported\n" );
60
				continue;
61
			}
62
63
			$this->output( "Importing $page\n" );
64
			$url = wfAppendQuery( $baseUrl, [
65
				'action' => 'raw',
66
				'title' => "MediaWiki:{$page}" ] );
67
			$text = Http::get( $url, [], __METHOD__ );
68
69
			$wikiPage = WikiPage::factory( $title );
70
			$content = ContentHandler::makeContent( $text, $wikiPage->getTitle() );
0 ignored issues
show
Bug introduced by
It seems like $text defined by \Http::get($url, array(), __METHOD__) on line 67 can also be of type boolean; however, ContentHandler::makeContent() 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...
71
			$wikiPage->doEditContent( $content, "Importing from $url", 0, false, $user );
0 ignored issues
show
Security Bug introduced by
It seems like $user defined by \User::newFromName($username) on line 48 can also be of type false; however, WikiPage::doEditContent() does only seem to accept null|object<User>, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
72
		}
73
	}
74
75
	protected function fetchScriptList() {
76
		$data = [
77
			'action' => 'query',
78
			'format' => 'json',
79
			'list' => 'allpages',
80
			'apnamespace' => '8',
81
			'aplimit' => '500',
82
			'continue' => '',
83
		];
84
		$baseUrl = $this->getArg( 0 );
85
		$pages = [];
86
87
		while ( true ) {
88
			$url = wfAppendQuery( $baseUrl, $data );
89
			$strResult = Http::get( $url, [], __METHOD__ );
90
			$result = FormatJson::decode( $strResult, true );
0 ignored issues
show
Bug introduced by
It seems like $strResult defined by \Http::get($url, array(), __METHOD__) on line 89 can also be of type boolean; however, FormatJson::decode() 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...
91
92
			$page = null;
93
			foreach ( $result['query']['allpages'] as $page ) {
94
				if ( substr( $page['title'], -3 ) === '.js' ) {
95
					strtok( $page['title'], ':' );
96
					$pages[] = strtok( '' );
97
				}
98
			}
99
100
			if ( $page !== null ) {
101
				$this->output( "Fetched list up to {$page['title']}\n" );
102
			}
103
104
			if ( isset( $result['continue'] ) ) { // >= 1.21
105
				$data = array_replace( $data, $result['continue'] );
106
			} elseif ( isset( $result['query-continue']['allpages'] ) ) { // <= 1.20
107
				$data = array_replace( $data, $result['query-continue']['allpages'] );
108
			} else {
109
				break;
110
			}
111
		}
112
113
		return $pages;
114
	}
115
}
116
117
$maintClass = 'ImportSiteScripts';
118
require_once RUN_MAINTENANCE_IF_MAIN;
119