Completed
Branch master (0c9f05)
by
unknown
29:21
created

HTMLFormField::getOOUI()   B

Complexity

Conditions 9
Paths 65

Size

Total Lines 56
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 9
eloc 32
nc 65
nop 1
dl 0
loc 56
rs 7.1584
c 1
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
2
3
/**
4
 * The parent class to generate form fields.  Any field type should
5
 * be a subclass of this.
6
 */
7
abstract class HTMLFormField {
8
	public $mParams;
9
10
	protected $mValidationCallback;
11
	protected $mFilterCallback;
12
	protected $mName;
13
	protected $mDir;
14
	protected $mLabel; # String label, as HTML. Set on construction.
15
	protected $mID;
16
	protected $mClass = '';
17
	protected $mVFormClass = '';
18
	protected $mHelpClass = false;
19
	protected $mDefault;
20
	protected $mOptions = false;
21
	protected $mOptionsLabelsNotFromMessage = false;
22
	protected $mHideIf = null;
23
24
	/**
25
	 * @var bool If true will generate an empty div element with no label
26
	 * @since 1.22
27
	 */
28
	protected $mShowEmptyLabels = true;
29
30
	/**
31
	 * @var HTMLForm|null
32
	 */
33
	public $mParent;
34
35
	/**
36
	 * This function must be implemented to return the HTML to generate
37
	 * the input object itself.  It should not implement the surrounding
38
	 * table cells/rows, or labels/help messages.
39
	 *
40
	 * @param string $value The value to set the input to; eg a default
41
	 *     text for a text input.
42
	 *
43
	 * @return string Valid HTML.
44
	 */
45
	abstract function getInputHTML( $value );
46
47
	/**
48
	 * Same as getInputHTML, but returns an OOUI object.
49
	 * Defaults to false, which getOOUI will interpret as "use the HTML version"
50
	 *
51
	 * @param string $value
52
	 * @return OOUI\Widget|false
53
	 */
54
	function getInputOOUI( $value ) {
55
		return false;
56
	}
57
58
	/**
59
	 * True if this field type is able to display errors; false if validation errors need to be
60
	 * displayed in the main HTMLForm error area.
61
	 * @return bool
62
	 */
63
	public function canDisplayErrors() {
64
		return true;
65
	}
66
67
	/**
68
	 * Get a translated interface message
69
	 *
70
	 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
71
	 * and wfMessage() otherwise.
72
	 *
73
	 * Parameters are the same as wfMessage().
74
	 *
75
	 * @return Message
76
	 */
77
	function msg() {
78
		$args = func_get_args();
79
80
		if ( $this->mParent ) {
81
			$callback = [ $this->mParent, 'msg' ];
82
		} else {
83
			$callback = 'wfMessage';
84
		}
85
86
		return call_user_func_array( $callback, $args );
87
	}
88
89
	/**
90
	 * If this field has a user-visible output or not. If not,
91
	 * it will not be rendered
92
	 *
93
	 * @return bool
94
	 */
95
	public function hasVisibleOutput() {
96
		return true;
97
	}
98
99
	/**
100
	 * Fetch a field value from $alldata for the closest field matching a given
101
	 * name.
102
	 *
103
	 * This is complex because it needs to handle array fields like the user
104
	 * would expect. The general algorithm is to look for $name as a sibling
105
	 * of $this, then a sibling of $this's parent, and so on. Keeping in mind
106
	 * that $name itself might be referencing an array.
107
	 *
108
	 * @param array $alldata
109
	 * @param string $name
110
	 * @return string
111
	 */
112
	protected function getNearestFieldByName( $alldata, $name ) {
113
		$tmp = $this->mName;
114
		$thisKeys = [];
115
		while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
116
			array_unshift( $thisKeys, $m[2] );
117
			$tmp = $m[1];
118
		}
119
		if ( substr( $tmp, 0, 2 ) == 'wp' &&
120
			!array_key_exists( $tmp, $alldata ) &&
121
			array_key_exists( substr( $tmp, 2 ), $alldata )
122
		) {
123
			// Adjust for name mangling.
124
			$tmp = substr( $tmp, 2 );
125
		}
126
		array_unshift( $thisKeys, $tmp );
127
128
		$tmp = $name;
129
		$nameKeys = [];
130
		while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
131
			array_unshift( $nameKeys, $m[2] );
132
			$tmp = $m[1];
133
		}
134
		array_unshift( $nameKeys, $tmp );
135
136
		$testValue = '';
137
		for ( $i = count( $thisKeys ) - 1; $i >= 0; $i-- ) {
138
			$keys = array_merge( array_slice( $thisKeys, 0, $i ), $nameKeys );
139
			$data = $alldata;
140
			while ( $keys ) {
141
				$key = array_shift( $keys );
142
				if ( !is_array( $data ) || !array_key_exists( $key, $data ) ) {
143
					continue 2;
144
				}
145
				$data = $data[$key];
146
			}
147
			$testValue = (string)$data;
148
			break;
149
		}
150
151
		return $testValue;
152
	}
153
154
	/**
155
	 * Helper function for isHidden to handle recursive data structures.
156
	 *
157
	 * @param array $alldata
158
	 * @param array $params
159
	 * @return bool
160
	 * @throws MWException
161
	 */
162
	protected function isHiddenRecurse( array $alldata, array $params ) {
163
		$origParams = $params;
164
		$op = array_shift( $params );
165
166
		try {
167
			switch ( $op ) {
168 View Code Duplication
				case 'AND':
169
					foreach ( $params as $i => $p ) {
170
						if ( !is_array( $p ) ) {
171
							throw new MWException(
172
								"Expected array, found " . gettype( $p ) . " at index $i"
173
							);
174
						}
175
						if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
176
							return false;
177
						}
178
					}
179
					return true;
180
181
				case 'OR':
182
					foreach ( $params as $i => $p ) {
183
						if ( !is_array( $p ) ) {
184
							throw new MWException(
185
								"Expected array, found " . gettype( $p ) . " at index $i"
186
							);
187
						}
188
						if ( $this->isHiddenRecurse( $alldata, $p ) ) {
189
							return true;
190
						}
191
					}
192
					return false;
193
194 View Code Duplication
				case 'NAND':
195
					foreach ( $params as $i => $p ) {
196
						if ( !is_array( $p ) ) {
197
							throw new MWException(
198
								"Expected array, found " . gettype( $p ) . " at index $i"
199
							);
200
						}
201
						if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
202
							return true;
203
						}
204
					}
205
					return false;
206
207
				case 'NOR':
208
					foreach ( $params as $i => $p ) {
209
						if ( !is_array( $p ) ) {
210
							throw new MWException(
211
								"Expected array, found " . gettype( $p ) . " at index $i"
212
							);
213
						}
214
						if ( $this->isHiddenRecurse( $alldata, $p ) ) {
215
							return false;
216
						}
217
					}
218
					return true;
219
220
				case 'NOT':
221
					if ( count( $params ) !== 1 ) {
222
						throw new MWException( "NOT takes exactly one parameter" );
223
					}
224
					$p = $params[0];
225
					if ( !is_array( $p ) ) {
226
						throw new MWException(
227
							"Expected array, found " . gettype( $p ) . " at index 0"
228
						);
229
					}
230
					return !$this->isHiddenRecurse( $alldata, $p );
231
232
				case '===':
233
				case '!==':
0 ignored issues
show
Coding Style introduced by
There must be a comment when fall-through is intentional in a non-empty case body
Loading history...
234
					if ( count( $params ) !== 2 ) {
235
						throw new MWException( "$op takes exactly two parameters" );
236
					}
237
					list( $field, $value ) = $params;
238
					if ( !is_string( $field ) || !is_string( $value ) ) {
239
						throw new MWException( "Parameters for $op must be strings" );
240
					}
241
					$testValue = $this->getNearestFieldByName( $alldata, $field );
242
					switch ( $op ) {
243
						case '===':
244
							return ( $value === $testValue );
245
						case '!==':
246
							return ( $value !== $testValue );
247
					}
248
249
				default:
250
					throw new MWException( "Unknown operation" );
251
			}
252
		} catch ( Exception $ex ) {
253
			throw new MWException(
254
				"Invalid hide-if specification for $this->mName: " .
255
				$ex->getMessage() . " in " . var_export( $origParams, true ),
256
				0, $ex
257
			);
258
		}
259
	}
260
261
	/**
262
	 * Test whether this field is supposed to be hidden, based on the values of
263
	 * the other form fields.
264
	 *
265
	 * @since 1.23
266
	 * @param array $alldata The data collected from the form
267
	 * @return bool
268
	 */
269
	function isHidden( $alldata ) {
270
		if ( !$this->mHideIf ) {
271
			return false;
272
		}
273
274
		return $this->isHiddenRecurse( $alldata, $this->mHideIf );
275
	}
276
277
	/**
278
	 * Override this function if the control can somehow trigger a form
279
	 * submission that shouldn't actually submit the HTMLForm.
280
	 *
281
	 * @since 1.23
282
	 * @param string|array $value The value the field was submitted with
283
	 * @param array $alldata The data collected from the form
284
	 *
285
	 * @return bool True to cancel the submission
286
	 */
287
	function cancelSubmit( $value, $alldata ) {
288
		return false;
289
	}
290
291
	/**
292
	 * Override this function to add specific validation checks on the
293
	 * field input.  Don't forget to call parent::validate() to ensure
294
	 * that the user-defined callback mValidationCallback is still run
295
	 *
296
	 * @param string|array $value The value the field was submitted with
297
	 * @param array $alldata The data collected from the form
298
	 *
299
	 * @return bool|string True on success, or String error to display, or
300
	 *   false to fail validation without displaying an error.
301
	 */
302
	function validate( $value, $alldata ) {
303
		if ( $this->isHidden( $alldata ) ) {
304
			return true;
305
		}
306
307 View Code Duplication
		if ( isset( $this->mParams['required'] )
308
			&& $this->mParams['required'] !== false
309
			&& $value === ''
310
		) {
311
			return $this->msg( 'htmlform-required' )->parse();
312
		}
313
314
		if ( isset( $this->mValidationCallback ) ) {
315
			return call_user_func( $this->mValidationCallback, $value, $alldata, $this->mParent );
316
		}
317
318
		return true;
319
	}
320
321
	function filter( $value, $alldata ) {
322
		if ( isset( $this->mFilterCallback ) ) {
323
			$value = call_user_func( $this->mFilterCallback, $value, $alldata, $this->mParent );
324
		}
325
326
		return $value;
327
	}
328
329
	/**
330
	 * Should this field have a label, or is there no input element with the
331
	 * appropriate id for the label to point to?
332
	 *
333
	 * @return bool True to output a label, false to suppress
334
	 */
335
	protected function needsLabel() {
336
		return true;
337
	}
338
339
	/**
340
	 * Tell the field whether to generate a separate label element if its label
341
	 * is blank.
342
	 *
343
	 * @since 1.22
344
	 *
345
	 * @param bool $show Set to false to not generate a label.
346
	 * @return void
347
	 */
348
	public function setShowEmptyLabel( $show ) {
349
		$this->mShowEmptyLabels = $show;
350
	}
351
352
	/**
353
	 * Can we assume that the request is an attempt to submit a HTMLForm, as opposed to an attempt to
354
	 * just view it? This can't normally be distinguished for e.g. checkboxes.
355
	 *
356
	 * Returns true if the request has a field for a CSRF token (wpEditToken) or a form identifier
357
	 * (wpFormIdentifier).
358
	 *
359
	 * @param WebRequest $request
360
	 * @return boolean
361
	 */
362
	protected function isSubmitAttempt( WebRequest $request ) {
363
		return $request->getCheck( 'wpEditToken' ) || $request->getCheck( 'wpFormIdentifier' );
364
	}
365
366
	/**
367
	 * Get the value that this input has been set to from a posted form,
368
	 * or the input's default value if it has not been set.
369
	 *
370
	 * @param WebRequest $request
371
	 * @return string The value
372
	 */
373
	function loadDataFromRequest( $request ) {
374
		if ( $request->getCheck( $this->mName ) ) {
375
			return $request->getText( $this->mName );
376
		} else {
377
			return $this->getDefault();
378
		}
379
	}
380
381
	/**
382
	 * Initialise the object
383
	 *
384
	 * @param array $params Associative Array. See HTMLForm doc for syntax.
385
	 *
386
	 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
387
	 * @throws MWException
388
	 */
389
	function __construct( $params ) {
390
		$this->mParams = $params;
391
392
		if ( isset( $params['parent'] ) && $params['parent'] instanceof HTMLForm ) {
393
			$this->mParent = $params['parent'];
394
		}
395
396
		# Generate the label from a message, if possible
397
		if ( isset( $params['label-message'] ) ) {
398
			$this->mLabel = $this->getMessage( $params['label-message'] )->parse();
399
		} elseif ( isset( $params['label'] ) ) {
400
			if ( $params['label'] === '&#160;' ) {
401
				// Apparently some things set &nbsp directly and in an odd format
402
				$this->mLabel = '&#160;';
403
			} else {
404
				$this->mLabel = htmlspecialchars( $params['label'] );
405
			}
406
		} elseif ( isset( $params['label-raw'] ) ) {
407
			$this->mLabel = $params['label-raw'];
408
		}
409
410
		$this->mName = "wp{$params['fieldname']}";
411
		if ( isset( $params['name'] ) ) {
412
			$this->mName = $params['name'];
413
		}
414
415
		if ( isset( $params['dir'] ) ) {
416
			$this->mDir = $params['dir'];
417
		}
418
419
		$validName = Sanitizer::escapeId( $this->mName );
420
		$validName = str_replace( [ '.5B', '.5D' ], [ '[', ']' ], $validName );
421
		if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
422
			throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
423
		}
424
425
		$this->mID = "mw-input-{$this->mName}";
426
427
		if ( isset( $params['default'] ) ) {
428
			$this->mDefault = $params['default'];
429
		}
430
431
		if ( isset( $params['id'] ) ) {
432
			$id = $params['id'];
433
			$validId = Sanitizer::escapeId( $id );
434
435
			if ( $id != $validId ) {
436
				throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
437
			}
438
439
			$this->mID = $id;
440
		}
441
442
		if ( isset( $params['cssclass'] ) ) {
443
			$this->mClass = $params['cssclass'];
444
		}
445
446
		if ( isset( $params['csshelpclass'] ) ) {
447
			$this->mHelpClass = $params['csshelpclass'];
448
		}
449
450
		if ( isset( $params['validation-callback'] ) ) {
451
			$this->mValidationCallback = $params['validation-callback'];
452
		}
453
454
		if ( isset( $params['filter-callback'] ) ) {
455
			$this->mFilterCallback = $params['filter-callback'];
456
		}
457
458
		if ( isset( $params['flatlist'] ) ) {
459
			$this->mClass .= ' mw-htmlform-flatlist';
460
		}
461
462
		if ( isset( $params['hidelabel'] ) ) {
463
			$this->mShowEmptyLabels = false;
464
		}
465
466
		if ( isset( $params['hide-if'] ) ) {
467
			$this->mHideIf = $params['hide-if'];
468
		}
469
	}
470
471
	/**
472
	 * Get the complete table row for the input, including help text,
473
	 * labels, and whatever.
474
	 *
475
	 * @param string $value The value to set the input to.
476
	 *
477
	 * @return string Complete HTML table row.
478
	 */
479
	function getTableRow( $value ) {
480
		list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
481
		$inputHtml = $this->getInputHTML( $value );
482
		$fieldType = get_class( $this );
483
		$helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
0 ignored issues
show
Bug introduced by
It seems like $this->getHelpText() targeting HTMLFormField::getHelpText() can also be of type array<integer,?,{"0":"?"}>; however, HTMLFormField::getHelpTextHtmlTable() does only seem to accept string|null, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
484
		$cellAttributes = [];
485
		$rowAttributes = [];
486
		$rowClasses = '';
487
488
		if ( !empty( $this->mParams['vertical-label'] ) ) {
489
			$cellAttributes['colspan'] = 2;
490
			$verticalLabel = true;
491
		} else {
492
			$verticalLabel = false;
493
		}
494
495
		$label = $this->getLabelHtml( $cellAttributes );
496
497
		$field = Html::rawElement(
498
			'td',
499
			[ 'class' => 'mw-input' ] + $cellAttributes,
500
			$inputHtml . "\n$errors"
501
		);
502
503
		if ( $this->mHideIf ) {
504
			$rowAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
505
			$rowClasses .= ' mw-htmlform-hide-if';
506
		}
507
508
		if ( $verticalLabel ) {
509
			$html = Html::rawElement( 'tr',
510
				$rowAttributes + [ 'class' => "mw-htmlform-vertical-label $rowClasses" ], $label );
511
			$html .= Html::rawElement( 'tr',
512
				$rowAttributes + [
513
					'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
514
				],
515
				$field );
516
		} else {
517
			$html =
518
				Html::rawElement( 'tr',
519
					$rowAttributes + [
520
						'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
521
					],
522
					$label . $field );
523
		}
524
525
		return $html . $helptext;
526
	}
527
528
	/**
529
	 * Get the complete div for the input, including help text,
530
	 * labels, and whatever.
531
	 * @since 1.20
532
	 *
533
	 * @param string $value The value to set the input to.
534
	 *
535
	 * @return string Complete HTML table row.
536
	 */
537
	public function getDiv( $value ) {
538
		list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
539
		$inputHtml = $this->getInputHTML( $value );
540
		$fieldType = get_class( $this );
541
		$helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
0 ignored issues
show
Bug introduced by
It seems like $this->getHelpText() targeting HTMLFormField::getHelpText() can also be of type array<integer,?,{"0":"?"}>; however, HTMLFormField::getHelpTextHtmlDiv() does only seem to accept string|null, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
542
		$cellAttributes = [];
543
		$label = $this->getLabelHtml( $cellAttributes );
544
545
		$outerDivClass = [
546
			'mw-input',
547
			'mw-htmlform-nolabel' => ( $label === '' )
548
		];
549
550
		$horizontalLabel = isset( $this->mParams['horizontal-label'] )
551
			? $this->mParams['horizontal-label'] : false;
552
553
		if ( $horizontalLabel ) {
554
			$field = '&#160;' . $inputHtml . "\n$errors";
555
		} else {
556
			$field = Html::rawElement(
557
				'div',
558
				[ 'class' => $outerDivClass ] + $cellAttributes,
559
				$inputHtml . "\n$errors"
560
			);
561
		}
562
		$divCssClasses = [ "mw-htmlform-field-$fieldType",
563
			$this->mClass, $this->mVFormClass, $errorClass ];
564
565
		$wrapperAttributes = [
566
			'class' => $divCssClasses,
567
		];
568 View Code Duplication
		if ( $this->mHideIf ) {
569
			$wrapperAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
570
			$wrapperAttributes['class'][] = ' mw-htmlform-hide-if';
571
		}
572
		$html = Html::rawElement( 'div', $wrapperAttributes, $label . $field );
573
		$html .= $helptext;
574
575
		return $html;
576
	}
577
578
	/**
579
	 * Get the OOUI version of the div. Falls back to getDiv by default.
580
	 * @since 1.26
581
	 *
582
	 * @param string $value The value to set the input to.
583
	 *
584
	 * @return OOUI\FieldLayout|OOUI\ActionFieldLayout
585
	 */
586
	public function getOOUI( $value ) {
587
		$inputField = $this->getInputOOUI( $value );
588
589
		if ( !$inputField ) {
590
			// This field doesn't have an OOUI implementation yet at all. Fall back to getDiv() to
591
			// generate the whole field, label and errors and all, then wrap it in a Widget.
592
			// It might look weird, but it'll work OK.
593
			return $this->getFieldLayoutOOUI(
594
				new OOUI\Widget( [ 'content' => new OOUI\HtmlSnippet( $this->getDiv( $value ) ) ] ),
595
				[ 'infusable' => false, 'align' => 'top' ]
596
			);
597
		}
598
599
		$infusable = true;
600
		if ( is_string( $inputField ) ) {
601
			// We have an OOUI implementation, but it's not proper, and we got a load of HTML.
602
			// Cheat a little and wrap it in a widget. It won't be infusable, though, since client-side
603
			// JavaScript doesn't know how to rebuilt the contents.
604
			$inputField = new OOUI\Widget( [ 'content' => new OOUI\HtmlSnippet( $inputField ) ] );
605
			$infusable = false;
606
		}
607
608
		$fieldType = get_class( $this );
609
		$helpText = $this->getHelpText();
610
		$errors = $this->getErrorsRaw( $value );
611
		foreach ( $errors as &$error ) {
612
			$error = new OOUI\HtmlSnippet( $error );
613
		}
614
615
		$notices = $this->getNotices();
616
		foreach ( $notices as &$notice ) {
617
			$notice = new OOUI\HtmlSnippet( $notice );
618
		}
619
620
		$config = [
621
			'classes' => [ "mw-htmlform-field-$fieldType", $this->mClass ],
622
			'align' => $this->getLabelAlignOOUI(),
623
			'help' => $helpText !== null ? new OOUI\HtmlSnippet( $helpText ) : null,
0 ignored issues
show
Bug introduced by
It seems like $helpText defined by $this->getHelpText() on line 609 can also be of type array<integer,?,{"0":"?"}>; however, OOUI\HtmlSnippet::__construct() 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...
624
			'errors' => $errors,
625
			'notices' => $notices,
626
			'infusable' => $infusable,
627
		];
628
629
		if ( $infusable && $this->shouldInfuseOOUI() ) {
630
			$this->mParent->getOutput()->addModules( 'oojs-ui-core' );
631
			$config['classes'][] = 'mw-htmlform-field-autoinfuse';
632
		}
633
634
		// the element could specify, that the label doesn't need to be added
635
		$label = $this->getLabel();
636
		if ( $label ) {
637
			$config['label'] = new OOUI\HtmlSnippet( $label );
638
		}
639
640
		return $this->getFieldLayoutOOUI( $inputField, $config );
641
	}
642
643
	/**
644
	 * Get label alignment when generating field for OOUI.
645
	 * @return string 'left', 'right', 'top' or 'inline'
646
	 */
647
	protected function getLabelAlignOOUI() {
648
		return 'top';
649
	}
650
651
	/**
652
	 * Get a FieldLayout (or subclass thereof) to wrap this field in when using OOUI output.
653
	 * @return OOUI\FieldLayout|OOUI\ActionFieldLayout
654
	 */
655
	protected function getFieldLayoutOOUI( $inputField, $config ) {
656
		if ( isset( $this->mClassWithButton ) ) {
657
			$buttonWidget = $this->mClassWithButton->getInputOOUI( '' );
0 ignored issues
show
Bug introduced by
The property mClassWithButton does not seem to exist. Did you mean mClass?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
658
			return new OOUI\ActionFieldLayout( $inputField, $buttonWidget, $config );
659
		}
660
		return new OOUI\FieldLayout( $inputField, $config );
661
	}
662
663
	/**
664
	 * Whether the field should be automatically infused. Note that all OOjs UI HTMLForm fields are
665
	 * infusable (you can call OO.ui.infuse() on them), but not all are infused by default, since
666
	 * there is no benefit in doing it e.g. for buttons and it's a small performance hit on page load.
667
	 *
668
	 * @return bool
669
	 */
670
	protected function shouldInfuseOOUI() {
671
		// Always infuse fields with help text, since the interface for it is nicer with JS
672
		return $this->getHelpText() !== null;
673
	}
674
675
	/**
676
	 * Get the complete raw fields for the input, including help text,
677
	 * labels, and whatever.
678
	 * @since 1.20
679
	 *
680
	 * @param string $value The value to set the input to.
681
	 *
682
	 * @return string Complete HTML table row.
683
	 */
684
	public function getRaw( $value ) {
685
		list( $errors, ) = $this->getErrorsAndErrorClass( $value );
686
		$inputHtml = $this->getInputHTML( $value );
687
		$helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
0 ignored issues
show
Bug introduced by
It seems like $this->getHelpText() targeting HTMLFormField::getHelpText() can also be of type array<integer,?,{"0":"?"}>; however, HTMLFormField::getHelpTextHtmlRaw() does only seem to accept string|null, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
688
		$cellAttributes = [];
689
		$label = $this->getLabelHtml( $cellAttributes );
690
691
		$html = "\n$errors";
692
		$html .= $label;
693
		$html .= $inputHtml;
694
		$html .= $helptext;
695
696
		return $html;
697
	}
698
699
	/**
700
	 * Get the complete field for the input, including help text,
701
	 * labels, and whatever. Fall back from 'vform' to 'div' when not overridden.
702
	 *
703
	 * @since 1.25
704
	 * @param string $value The value to set the input to.
705
	 * @return string Complete HTML field.
706
	 */
707
	public function getVForm( $value ) {
708
		// Ewwww
709
		$this->mVFormClass = ' mw-ui-vform-field';
710
		return $this->getDiv( $value );
711
	}
712
713
	/**
714
	 * Get the complete field as an inline element.
715
	 * @since 1.25
716
	 * @param string $value The value to set the input to.
717
	 * @return string Complete HTML inline element
718
	 */
719
	public function getInline( $value ) {
720
		list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
0 ignored issues
show
Unused Code introduced by
The assignment to $errorClass is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
721
		$inputHtml = $this->getInputHTML( $value );
722
		$helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
0 ignored issues
show
Bug introduced by
It seems like $this->getHelpText() targeting HTMLFormField::getHelpText() can also be of type array<integer,?,{"0":"?"}>; however, HTMLFormField::getHelpTextHtmlDiv() does only seem to accept string|null, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
723
		$cellAttributes = [];
724
		$label = $this->getLabelHtml( $cellAttributes );
725
726
		$html = "\n" . $errors .
727
			$label . '&#160;' .
728
			$inputHtml .
729
			$helptext;
730
731
		return $html;
732
	}
733
734
	/**
735
	 * Generate help text HTML in table format
736
	 * @since 1.20
737
	 *
738
	 * @param string|null $helptext
739
	 * @return string
740
	 */
741
	public function getHelpTextHtmlTable( $helptext ) {
742
		if ( is_null( $helptext ) ) {
743
			return '';
744
		}
745
746
		$rowAttributes = [];
747 View Code Duplication
		if ( $this->mHideIf ) {
748
			$rowAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
749
			$rowAttributes['class'] = 'mw-htmlform-hide-if';
750
		}
751
752
		$tdClasses = [ 'htmlform-tip' ];
753
		if ( $this->mHelpClass !== false ) {
754
			$tdClasses[] = $this->mHelpClass;
755
		}
756
		$row = Html::rawElement( 'td', [ 'colspan' => 2, 'class' => $tdClasses ], $helptext );
757
		$row = Html::rawElement( 'tr', $rowAttributes, $row );
758
759
		return $row;
760
	}
761
762
	/**
763
	 * Generate help text HTML in div format
764
	 * @since 1.20
765
	 *
766
	 * @param string|null $helptext
767
	 *
768
	 * @return string
769
	 */
770
	public function getHelpTextHtmlDiv( $helptext ) {
771
		if ( is_null( $helptext ) ) {
772
			return '';
773
		}
774
775
		$wrapperAttributes = [
776
			'class' => 'htmlform-tip',
777
		];
778
		if ( $this->mHelpClass !== false ) {
779
			$wrapperAttributes['class'] .= " {$this->mHelpClass}";
780
		}
781 View Code Duplication
		if ( $this->mHideIf ) {
782
			$wrapperAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
783
			$wrapperAttributes['class'] .= ' mw-htmlform-hide-if';
784
		}
785
		$div = Html::rawElement( 'div', $wrapperAttributes, $helptext );
786
787
		return $div;
788
	}
789
790
	/**
791
	 * Generate help text HTML formatted for raw output
792
	 * @since 1.20
793
	 *
794
	 * @param string|null $helptext
795
	 * @return string
796
	 */
797
	public function getHelpTextHtmlRaw( $helptext ) {
798
		return $this->getHelpTextHtmlDiv( $helptext );
799
	}
800
801
	/**
802
	 * Determine the help text to display
803
	 * @since 1.20
804
	 * @return string HTML
805
	 */
806
	public function getHelpText() {
807
		$helptext = null;
808
809
		if ( isset( $this->mParams['help-message'] ) ) {
810
			$this->mParams['help-messages'] = [ $this->mParams['help-message'] ];
811
		}
812
813
		if ( isset( $this->mParams['help-messages'] ) ) {
814
			foreach ( $this->mParams['help-messages'] as $msg ) {
815
				$msg = $this->getMessage( $msg );
816
817
				if ( $msg->exists() ) {
818
					if ( is_null( $helptext ) ) {
819
						$helptext = '';
820
					} else {
821
						$helptext .= $this->msg( 'word-separator' )->escaped(); // some space
822
					}
823
					$helptext .= $msg->parse(); // Append message
824
				}
825
			}
826
		} elseif ( isset( $this->mParams['help'] ) ) {
827
			$helptext = $this->mParams['help'];
828
		}
829
830
		return $helptext;
831
	}
832
833
	/**
834
	 * Determine form errors to display and their classes
835
	 * @since 1.20
836
	 *
837
	 * @param string $value The value of the input
838
	 * @return array array( $errors, $errorClass )
839
	 */
840
	public function getErrorsAndErrorClass( $value ) {
841
		$errors = $this->validate( $value, $this->mParent->mFieldData );
842
843
		if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
844
			$errors = '';
845
			$errorClass = '';
846
		} else {
847
			$errors = self::formatErrors( $errors );
848
			$errorClass = 'mw-htmlform-invalid-input';
849
		}
850
851
		return [ $errors, $errorClass ];
852
	}
853
854
	/**
855
	 * Determine form errors to display, returning them in an array.
856
	 *
857
	 * @since 1.26
858
	 * @param string $value The value of the input
859
	 * @return string[] Array of error HTML strings
860
	 */
861
	public function getErrorsRaw( $value ) {
862
		$errors = $this->validate( $value, $this->mParent->mFieldData );
863
864
		if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
865
			$errors = [];
866
		}
867
868
		if ( !is_array( $errors ) ) {
869
			$errors = [ $errors ];
870
		}
871
		foreach ( $errors as &$error ) {
872
			if ( $error instanceof Message ) {
873
				$error = $error->parse();
874
			}
875
		}
876
877
		return $errors;
878
	}
879
880
	/**
881
	 * Determine notices to display for the field.
882
	 *
883
	 * @since 1.28
884
	 * @return string[]
885
	 */
886
	function getNotices() {
887
		$notices = [];
888
889
		if ( isset( $this->mParams['notice-message'] ) ) {
890
			$notices[] = $this->getMessage( $this->mParams['notice-message'] )->parse();
891
		}
892
893
		if ( isset( $this->mParams['notice-messages'] ) ) {
894
			foreach ( $this->mParams['notice-messages'] as $msg ) {
895
				$notices[] = $this->getMessage( $msg )->parse();
896
			}
897
		} elseif ( isset( $this->mParams['notice'] ) ) {
898
			$notices[] = $this->mParams['notice'];
899
		}
900
901
		return $notices;
902
	}
903
904
	/**
905
	 * @return string HTML
906
	 */
907
	function getLabel() {
908
		return is_null( $this->mLabel ) ? '' : $this->mLabel;
909
	}
910
911
	function getLabelHtml( $cellAttributes = [] ) {
912
		# Don't output a for= attribute for labels with no associated input.
913
		# Kind of hacky here, possibly we don't want these to be <label>s at all.
914
		$for = [];
915
916
		if ( $this->needsLabel() ) {
917
			$for['for'] = $this->mID;
918
		}
919
920
		$labelValue = trim( $this->getLabel() );
921
		$hasLabel = false;
922
		if ( $labelValue !== '&#160;' && $labelValue !== '' ) {
923
			$hasLabel = true;
924
		}
925
926
		$displayFormat = $this->mParent->getDisplayFormat();
927
		$html = '';
928
		$horizontalLabel = isset( $this->mParams['horizontal-label'] )
929
			? $this->mParams['horizontal-label'] : false;
930
931
		if ( $displayFormat === 'table' ) {
932
			$html =
933
				Html::rawElement( 'td',
934
					[ 'class' => 'mw-label' ] + $cellAttributes,
935
					Html::rawElement( 'label', $for, $labelValue ) );
936
		} elseif ( $hasLabel || $this->mShowEmptyLabels ) {
937
			if ( $displayFormat === 'div' && !$horizontalLabel ) {
938
				$html =
939
					Html::rawElement( 'div',
940
						[ 'class' => 'mw-label' ] + $cellAttributes,
941
						Html::rawElement( 'label', $for, $labelValue ) );
942
			} else {
943
				$html = Html::rawElement( 'label', $for, $labelValue );
944
			}
945
		}
946
947
		return $html;
948
	}
949
950
	function getDefault() {
951
		if ( isset( $this->mDefault ) ) {
952
			return $this->mDefault;
953
		} else {
954
			return null;
955
		}
956
	}
957
958
	/**
959
	 * Returns the attributes required for the tooltip and accesskey.
960
	 *
961
	 * @return array Attributes
962
	 */
963
	public function getTooltipAndAccessKey() {
964
		if ( empty( $this->mParams['tooltip'] ) ) {
965
			return [];
966
		}
967
968
		return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
969
	}
970
971
	/**
972
	 * Returns the given attributes from the parameters
973
	 *
974
	 * @param array $list List of attributes to get
975
	 * @return array Attributes
976
	 */
977
	public function getAttributes( array $list ) {
978
		static $boolAttribs = [ 'disabled', 'required', 'autofocus', 'multiple', 'readonly' ];
979
980
		$ret = [];
981
		foreach ( $list as $key ) {
982
			if ( in_array( $key, $boolAttribs ) ) {
983
				if ( !empty( $this->mParams[$key] ) ) {
984
					$ret[$key] = '';
985
				}
986
			} elseif ( isset( $this->mParams[$key] ) ) {
987
				$ret[$key] = $this->mParams[$key];
988
			}
989
		}
990
991
		return $ret;
992
	}
993
994
	/**
995
	 * Given an array of msg-key => value mappings, returns an array with keys
996
	 * being the message texts. It also forces values to strings.
997
	 *
998
	 * @param array $options
999
	 * @return array
1000
	 */
1001
	private function lookupOptionsKeys( $options ) {
1002
		$ret = [];
1003
		foreach ( $options as $key => $value ) {
1004
			$key = $this->msg( $key )->plain();
1005
			$ret[$key] = is_array( $value )
1006
				? $this->lookupOptionsKeys( $value )
1007
				: strval( $value );
1008
		}
1009
		return $ret;
1010
	}
1011
1012
	/**
1013
	 * Recursively forces values in an array to strings, because issues arise
1014
	 * with integer 0 as a value.
1015
	 *
1016
	 * @param array $array
1017
	 * @return array
1018
	 */
1019
	static function forceToStringRecursive( $array ) {
1020
		if ( is_array( $array ) ) {
1021
			return array_map( [ __CLASS__, 'forceToStringRecursive' ], $array );
1022
		} else {
1023
			return strval( $array );
1024
		}
1025
	}
1026
1027
	/**
1028
	 * Fetch the array of options from the field's parameters. In order, this
1029
	 * checks 'options-messages', 'options', then 'options-message'.
1030
	 *
1031
	 * @return array|null Options array
1032
	 */
1033
	public function getOptions() {
1034
		if ( $this->mOptions === false ) {
1035
			if ( array_key_exists( 'options-messages', $this->mParams ) ) {
1036
				$this->mOptions = $this->lookupOptionsKeys( $this->mParams['options-messages'] );
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->lookupOptionsKeys...ms['options-messages']) of type array is incompatible with the declared type boolean of property $mOptions.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
1037
			} elseif ( array_key_exists( 'options', $this->mParams ) ) {
1038
				$this->mOptionsLabelsNotFromMessage = true;
1039
				$this->mOptions = self::forceToStringRecursive( $this->mParams['options'] );
0 ignored issues
show
Documentation Bug introduced by
It seems like self::forceToStringRecur...is->mParams['options']) of type array or string is incompatible with the declared type boolean of property $mOptions.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
1040
			} elseif ( array_key_exists( 'options-message', $this->mParams ) ) {
1041
				/** @todo This is copied from Xml::listDropDown(), deprecate/avoid duplication? */
1042
				$message = $this->getMessage( $this->mParams['options-message'] )->inContentLanguage()->plain();
1043
1044
				$optgroup = false;
1045
				$this->mOptions = [];
0 ignored issues
show
Documentation Bug introduced by
It seems like array() of type array is incompatible with the declared type boolean of property $mOptions.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
1046
				foreach ( explode( "\n", $message ) as $option ) {
1047
					$value = trim( $option );
1048
					if ( $value == '' ) {
1049
						continue;
1050
					} elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
1051
						# A new group is starting...
1052
						$value = trim( substr( $value, 1 ) );
1053
						$optgroup = $value;
1054
					} elseif ( substr( $value, 0, 2 ) == '**' ) {
1055
						# groupmember
1056
						$opt = trim( substr( $value, 2 ) );
1057
						if ( $optgroup === false ) {
1058
							$this->mOptions[$opt] = $opt;
1059
						} else {
1060
							$this->mOptions[$optgroup][$opt] = $opt;
1061
						}
1062
					} else {
1063
						# groupless reason list
1064
						$optgroup = false;
1065
						$this->mOptions[$option] = $option;
1066
					}
1067
				}
1068
			} else {
1069
				$this->mOptions = null;
1070
			}
1071
		}
1072
1073
		return $this->mOptions;
1074
	}
1075
1076
	/**
1077
	 * Get options and make them into arrays suitable for OOUI.
1078
	 * @return array Options for inclusion in a select or whatever.
1079
	 */
1080
	public function getOptionsOOUI() {
1081
		$oldoptions = $this->getOptions();
1082
1083
		if ( $oldoptions === null ) {
1084
			return null;
1085
		}
1086
1087
		$options = [];
1088
1089
		foreach ( $oldoptions as $text => $data ) {
0 ignored issues
show
Bug introduced by
The expression $oldoptions of type array|string|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...
1090
			$options[] = [
1091
				'data' => (string)$data,
1092
				'label' => (string)$text,
1093
			];
1094
		}
1095
1096
		return $options;
1097
	}
1098
1099
	/**
1100
	 * flatten an array of options to a single array, for instance,
1101
	 * a set of "<options>" inside "<optgroups>".
1102
	 *
1103
	 * @param array $options Associative Array with values either Strings or Arrays
1104
	 * @return array Flattened input
1105
	 */
1106
	public static function flattenOptions( $options ) {
1107
		$flatOpts = [];
1108
1109
		foreach ( $options as $value ) {
1110
			if ( is_array( $value ) ) {
1111
				$flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1112
			} else {
1113
				$flatOpts[] = $value;
1114
			}
1115
		}
1116
1117
		return $flatOpts;
1118
	}
1119
1120
	/**
1121
	 * Formats one or more errors as accepted by field validation-callback.
1122
	 *
1123
	 * @param string|Message|array $errors Array of strings or Message instances
1124
	 * @return string HTML
1125
	 * @since 1.18
1126
	 */
1127
	protected static function formatErrors( $errors ) {
1128
		if ( is_array( $errors ) && count( $errors ) === 1 ) {
1129
			$errors = array_shift( $errors );
1130
		}
1131
1132
		if ( is_array( $errors ) ) {
1133
			$lines = [];
1134
			foreach ( $errors as $error ) {
1135
				if ( $error instanceof Message ) {
1136
					$lines[] = Html::rawElement( 'li', [], $error->parse() );
1137
				} else {
1138
					$lines[] = Html::rawElement( 'li', [], $error );
1139
				}
1140
			}
1141
1142
			return Html::rawElement( 'ul', [ 'class' => 'error' ], implode( "\n", $lines ) );
1143
		} else {
1144
			if ( $errors instanceof Message ) {
1145
				$errors = $errors->parse();
1146
			}
1147
1148
			return Html::rawElement( 'span', [ 'class' => 'error' ], $errors );
1149
		}
1150
	}
1151
1152
	/**
1153
	 * Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a
1154
	 * name + parameters array) into a Message.
1155
	 * @param mixed $value
1156
	 * @return Message
1157
	 */
1158
	protected function getMessage( $value ) {
1159
		$message = Message::newFromSpecifier( $value );
1160
1161
		if ( $this->mParent ) {
1162
			$message->setContext( $this->mParent );
1163
		}
1164
1165
		return $message;
1166
	}
1167
1168
	/**
1169
	 * Skip this field when collecting data.
1170
	 * @param WebRequest $request
1171
	 * @return bool
1172
	 * @since 1.27
1173
	 */
1174
	public function skipLoadData( $request ) {
1175
		return !empty( $this->mParams['nodata'] );
1176
	}
1177
}
1178