ApiQueryAllMessages::execute()   F
last analyzed

Complexity

Conditions 36
Paths > 20000

Size

Total Lines 159
Code Lines 96

Duplication

Lines 3
Ratio 1.89 %

Importance

Changes 0
Metric Value
cc 36
eloc 96
c 0
b 0
f 0
nc 237888
nop 0
dl 3
loc 159
rs 2

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
2
/**
3
 *
4
 *
5
 * Created on Dec 1, 2007
6
 *
7
 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
8
 *
9
 * This program is free software; you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation; either version 2 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License along
20
 * with this program; if not, write to the Free Software Foundation, Inc.,
21
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22
 * http://www.gnu.org/copyleft/gpl.html
23
 *
24
 * @file
25
 */
26
27
/**
28
 * A query action to return messages from site message cache
29
 *
30
 * @ingroup API
31
 */
32
class ApiQueryAllMessages extends ApiQueryBase {
33
34
	public function __construct( ApiQuery $query, $moduleName ) {
35
		parent::__construct( $query, $moduleName, 'am' );
36
	}
37
38
	public function execute() {
39
		$params = $this->extractRequestParams();
40
41
		if ( is_null( $params['lang'] ) ) {
42
			$langObj = $this->getLanguage();
43
		} elseif ( !Language::isValidCode( $params['lang'] ) ) {
44
			$this->dieUsage( 'Invalid language code for parameter lang', 'invalidlang' );
45
		} else {
46
			$langObj = Language::factory( $params['lang'] );
47
		}
48
49
		if ( $params['enableparser'] ) {
50
			if ( !is_null( $params['title'] ) ) {
51
				$title = Title::newFromText( $params['title'] );
52
				if ( !$title || $title->isExternal() ) {
53
					$this->dieUsageMsg( [ 'invalidtitle', $params['title'] ] );
54
				}
55
			} else {
56
				$title = Title::newFromText( 'API' );
57
			}
58
		}
59
60
		$prop = array_flip( (array)$params['prop'] );
61
62
		// Determine which messages should we print
63
		if ( in_array( '*', $params['messages'] ) ) {
64
			$message_names = Language::getMessageKeysFor( $langObj->getCode() );
0 ignored issues
show
Bug introduced by
The variable $langObj 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...
65
			if ( $params['includelocal'] ) {
66
				$message_names = array_unique( array_merge(
67
					$message_names,
68
					// Pass in the content language code so we get local messages that have a
69
					// MediaWiki:msgkey page. We might theoretically miss messages that have no
70
					// MediaWiki:msgkey page but do have a MediaWiki:msgkey/lang page, but that's
71
					// just a stupid case.
72
					MessageCache::singleton()->getAllMessageKeys( $this->getConfig()->get( 'LanguageCode' ) )
73
				) );
74
			}
75
			sort( $message_names );
76
			$messages_target = $message_names;
77
		} else {
78
			$messages_target = $params['messages'];
79
		}
80
81
		// Filter messages that have the specified prefix
82
		// Because we sorted the message array earlier, they will appear in a clump:
83
		if ( isset( $params['prefix'] ) ) {
84
			$skip = false;
85
			$messages_filtered = [];
86
			foreach ( $messages_target as $message ) {
87
				// === 0: must be at beginning of string (position 0)
88
				if ( strpos( $message, $params['prefix'] ) === 0 ) {
89
					if ( !$skip ) {
90
						$skip = true;
91
					}
92
					$messages_filtered[] = $message;
93
				} elseif ( $skip ) {
94
					break;
95
				}
96
			}
97
			$messages_target = $messages_filtered;
98
		}
99
100
		// Filter messages that contain specified string
101
		if ( isset( $params['filter'] ) ) {
102
			$messages_filtered = [];
103
			foreach ( $messages_target as $message ) {
104
				// !== is used because filter can be at the beginning of the string
105
				if ( strpos( $message, $params['filter'] ) !== false ) {
106
					$messages_filtered[] = $message;
107
				}
108
			}
109
			$messages_target = $messages_filtered;
110
		}
111
112
		// Whether we have any sort of message customisation filtering
113
		$customiseFilterEnabled = $params['customised'] !== 'all';
114
		if ( $customiseFilterEnabled ) {
115
			global $wgContLang;
116
117
			$customisedMessages = AllMessagesTablePager::getCustomisedStatuses(
118
				array_map(
119
					[ $langObj, 'ucfirst' ],
120
					$messages_target
121
				),
122
				$langObj->getCode(),
123
				!$langObj->equals( $wgContLang )
124
			);
125
126
			$customised = $params['customised'] === 'modified';
127
		}
128
129
		// Get all requested messages and print the result
130
		$skip = !is_null( $params['from'] );
131
		$useto = !is_null( $params['to'] );
132
		$result = $this->getResult();
133
		foreach ( $messages_target as $message ) {
134
			// Skip all messages up to $params['from']
135
			if ( $skip && $message === $params['from'] ) {
136
				$skip = false;
137
			}
138
139
			if ( $useto && $message > $params['to'] ) {
140
				break;
141
			}
142
143
			if ( !$skip ) {
144
				$a = [
145
					'name' => $message,
146
					'normalizedname' => MessageCache::normalizeKey( $message ),
147
				];
148
149
				$args = [];
150 View Code Duplication
				if ( isset( $params['args'] ) && count( $params['args'] ) != 0 ) {
151
					$args = $params['args'];
152
				}
153
154
				if ( $customiseFilterEnabled ) {
155
					$messageIsCustomised = isset( $customisedMessages['pages'][$langObj->ucfirst( $message )] );
156
					if ( $customised === $messageIsCustomised ) {
157
						if ( $customised ) {
0 ignored issues
show
Bug introduced by
The variable $customised 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...
158
							$a['customised'] = true;
159
						}
160
					} else {
161
						continue;
162
					}
163
				}
164
165
				$msg = wfMessage( $message, $args )->inLanguage( $langObj );
166
167
				if ( !$msg->exists() ) {
168
					$a['missing'] = true;
169
				} else {
170
					// Check if the parser is enabled:
171
					if ( $params['enableparser'] ) {
172
						$msgString = $msg->title( $title )->text();
0 ignored issues
show
Bug introduced by
The variable $title 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...
Bug introduced by
It seems like $title can be null; however, title() 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...
173
					} else {
174
						$msgString = $msg->plain();
175
					}
176
					if ( !$params['nocontent'] ) {
177
						ApiResult::setContentValue( $a, 'content', $msgString );
178
					}
179
					if ( isset( $prop['default'] ) ) {
180
						$default = wfMessage( $message )->inLanguage( $langObj )->useDatabase( false );
181
						if ( !$default->exists() ) {
182
							$a['defaultmissing'] = true;
183
						} elseif ( $default->plain() != $msgString ) {
184
							$a['default'] = $default->plain();
185
						}
186
					}
187
				}
188
				$fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $a );
189
				if ( !$fit ) {
190
					$this->setContinueEnumParameter( 'from', $message );
191
					break;
192
				}
193
			}
194
		}
195
		$result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'message' );
196
	}
197
198
	public function getCacheMode( $params ) {
199
		if ( is_null( $params['lang'] ) ) {
200
			// Language not specified, will be fetched from preferences
201
			return 'anon-public-user-private';
202
		} elseif ( $params['enableparser'] ) {
203
			// User-specific parser options will be used
204
			return 'anon-public-user-private';
205
		} else {
206
			// OK to cache
207
			return 'public';
208
		}
209
	}
210
211
	public function getAllowedParams() {
212
		return [
213
			'messages' => [
214
				ApiBase::PARAM_DFLT => '*',
215
				ApiBase::PARAM_ISMULTI => true,
216
			],
217
			'prop' => [
218
				ApiBase::PARAM_ISMULTI => true,
219
				ApiBase::PARAM_TYPE => [
220
					'default'
221
				]
222
			],
223
			'enableparser' => false,
224
			'nocontent' => false,
225
			'includelocal' => false,
226
			'args' => [
227
				ApiBase::PARAM_ISMULTI => true,
228
				ApiBase::PARAM_ALLOW_DUPLICATES => true,
229
			],
230
			'filter' => [],
231
			'customised' => [
232
				ApiBase::PARAM_DFLT => 'all',
233
				ApiBase::PARAM_TYPE => [
234
					'all',
235
					'modified',
236
					'unmodified'
237
				]
238
			],
239
			'lang' => null,
240
			'from' => null,
241
			'to' => null,
242
			'title' => null,
243
			'prefix' => null,
244
		];
245
	}
246
247
	protected function getExamplesMessages() {
248
		return [
249
			'action=query&meta=allmessages&amprefix=ipb-'
250
				=> 'apihelp-query+allmessages-example-ipb',
251
			'action=query&meta=allmessages&ammessages=august|mainpage&amlang=de'
252
				=> 'apihelp-query+allmessages-example-de',
253
		];
254
	}
255
256
	public function getHelpUrls() {
257
		return 'https://www.mediawiki.org/wiki/API:Allmessages';
258
	}
259
}
260