Completed
Branch master (8ef871)
by
unknown
29:40
created

HTMLFormField::needsLabel()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 0
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
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
			!isset( $alldata[$tmp] ) &&
121
			isset( $alldata[substr( $tmp, 2 )] )
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 ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $keys of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
141
				$key = array_shift( $keys );
142
				if ( !is_array( $data ) || !isset( $data[$key] ) ) {
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 View Code Duplication
				case 'OR':
182
					foreach ( $params as $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 View Code Duplication
				case 'NOR':
208
					foreach ( $params as $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
	 * Get the value that this input has been set to from a posted form,
354
	 * or the input's default value if it has not been set.
355
	 *
356
	 * @param WebRequest $request
357
	 * @return string The value
358
	 */
359
	function loadDataFromRequest( $request ) {
360
		if ( $request->getCheck( $this->mName ) ) {
361
			return $request->getText( $this->mName );
362
		} else {
363
			return $this->getDefault();
364
		}
365
	}
366
367
	/**
368
	 * Initialise the object
369
	 *
370
	 * @param array $params Associative Array. See HTMLForm doc for syntax.
371
	 *
372
	 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
373
	 * @throws MWException
374
	 */
375
	function __construct( $params ) {
376
		$this->mParams = $params;
377
378
		if ( isset( $params['parent'] ) && $params['parent'] instanceof HTMLForm ) {
379
			$this->mParent = $params['parent'];
380
		}
381
382
		# Generate the label from a message, if possible
383 View Code Duplication
		if ( isset( $params['label-message'] ) ) {
384
			$msgInfo = $params['label-message'];
385
386
			if ( is_array( $msgInfo ) ) {
387
				$msg = array_shift( $msgInfo );
388
			} else {
389
				$msg = $msgInfo;
390
				$msgInfo = [];
391
			}
392
393
			$this->mLabel = $this->msg( $msg, $msgInfo )->parse();
394
		} elseif ( isset( $params['label'] ) ) {
395
			if ( $params['label'] === '&#160;' ) {
396
				// Apparently some things set &nbsp directly and in an odd format
397
				$this->mLabel = '&#160;';
398
			} else {
399
				$this->mLabel = htmlspecialchars( $params['label'] );
400
			}
401
		} elseif ( isset( $params['label-raw'] ) ) {
402
			$this->mLabel = $params['label-raw'];
403
		}
404
405
		$this->mName = "wp{$params['fieldname']}";
406
		if ( isset( $params['name'] ) ) {
407
			$this->mName = $params['name'];
408
		}
409
410
		if ( isset( $params['dir'] ) ) {
411
			$this->mDir = $params['dir'];
412
		}
413
414
		$validName = Sanitizer::escapeId( $this->mName );
415
		$validName = str_replace( [ '.5B', '.5D' ], [ '[', ']' ], $validName );
416
		if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
417
			throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
418
		}
419
420
		$this->mID = "mw-input-{$this->mName}";
421
422
		if ( isset( $params['default'] ) ) {
423
			$this->mDefault = $params['default'];
424
		}
425
426
		if ( isset( $params['id'] ) ) {
427
			$id = $params['id'];
428
			$validId = Sanitizer::escapeId( $id );
429
430
			if ( $id != $validId ) {
431
				throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
432
			}
433
434
			$this->mID = $id;
435
		}
436
437
		if ( isset( $params['cssclass'] ) ) {
438
			$this->mClass = $params['cssclass'];
439
		}
440
441
		if ( isset( $params['csshelpclass'] ) ) {
442
			$this->mHelpClass = $params['csshelpclass'];
443
		}
444
445
		if ( isset( $params['validation-callback'] ) ) {
446
			$this->mValidationCallback = $params['validation-callback'];
447
		}
448
449
		if ( isset( $params['filter-callback'] ) ) {
450
			$this->mFilterCallback = $params['filter-callback'];
451
		}
452
453
		if ( isset( $params['flatlist'] ) ) {
454
			$this->mClass .= ' mw-htmlform-flatlist';
455
		}
456
457
		if ( isset( $params['hidelabel'] ) ) {
458
			$this->mShowEmptyLabels = false;
459
		}
460
461
		if ( isset( $params['hide-if'] ) ) {
462
			$this->mHideIf = $params['hide-if'];
463
		}
464
	}
465
466
	/**
467
	 * Get the complete table row for the input, including help text,
468
	 * labels, and whatever.
469
	 *
470
	 * @param string $value The value to set the input to.
471
	 *
472
	 * @return string Complete HTML table row.
473
	 */
474
	function getTableRow( $value ) {
475
		list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
476
		$inputHtml = $this->getInputHTML( $value );
477
		$fieldType = get_class( $this );
478
		$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...
479
		$cellAttributes = [];
480
		$rowAttributes = [];
481
		$rowClasses = '';
482
483
		if ( !empty( $this->mParams['vertical-label'] ) ) {
484
			$cellAttributes['colspan'] = 2;
485
			$verticalLabel = true;
486
		} else {
487
			$verticalLabel = false;
488
		}
489
490
		$label = $this->getLabelHtml( $cellAttributes );
491
492
		$field = Html::rawElement(
493
			'td',
494
			[ 'class' => 'mw-input' ] + $cellAttributes,
495
			$inputHtml . "\n$errors"
496
		);
497
498
		if ( $this->mHideIf ) {
499
			$rowAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
500
			$rowClasses .= ' mw-htmlform-hide-if';
501
		}
502
503
		if ( $verticalLabel ) {
504
			$html = Html::rawElement( 'tr',
505
				$rowAttributes + [ 'class' => "mw-htmlform-vertical-label $rowClasses" ], $label );
506
			$html .= Html::rawElement( 'tr',
507
				$rowAttributes + [
508
					'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
509
				],
510
				$field );
511
		} else {
512
			$html =
513
				Html::rawElement( 'tr',
514
					$rowAttributes + [
515
						'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
516
					],
517
					$label . $field );
518
		}
519
520
		return $html . $helptext;
521
	}
522
523
	/**
524
	 * Get the complete div for the input, including help text,
525
	 * labels, and whatever.
526
	 * @since 1.20
527
	 *
528
	 * @param string $value The value to set the input to.
529
	 *
530
	 * @return string Complete HTML table row.
531
	 */
532
	public function getDiv( $value ) {
533
		list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
534
		$inputHtml = $this->getInputHTML( $value );
535
		$fieldType = get_class( $this );
536
		$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...
537
		$cellAttributes = [];
538
		$label = $this->getLabelHtml( $cellAttributes );
539
540
		$outerDivClass = [
541
			'mw-input',
542
			'mw-htmlform-nolabel' => ( $label === '' )
543
		];
544
545
		$horizontalLabel = isset( $this->mParams['horizontal-label'] )
546
			? $this->mParams['horizontal-label'] : false;
547
548
		if ( $horizontalLabel ) {
549
			$field = '&#160;' . $inputHtml . "\n$errors";
550
		} else {
551
			$field = Html::rawElement(
552
				'div',
553
				[ 'class' => $outerDivClass ] + $cellAttributes,
554
				$inputHtml . "\n$errors"
555
			);
556
		}
557
		$divCssClasses = [ "mw-htmlform-field-$fieldType",
558
			$this->mClass, $this->mVFormClass, $errorClass ];
559
560
		$wrapperAttributes = [
561
			'class' => $divCssClasses,
562
		];
563 View Code Duplication
		if ( $this->mHideIf ) {
564
			$wrapperAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
565
			$wrapperAttributes['class'][] = ' mw-htmlform-hide-if';
566
		}
567
		$html = Html::rawElement( 'div', $wrapperAttributes, $label . $field );
568
		$html .= $helptext;
569
570
		return $html;
571
	}
572
573
	/**
574
	 * Get the OOUI version of the div. Falls back to getDiv by default.
575
	 * @since 1.26
576
	 *
577
	 * @param string $value The value to set the input to.
578
	 *
579
	 * @return OOUI\FieldLayout|OOUI\ActionFieldLayout
580
	 */
581
	public function getOOUI( $value ) {
582
		$inputField = $this->getInputOOUI( $value );
583
584
		if ( !$inputField ) {
585
			// This field doesn't have an OOUI implementation yet at all. Fall back to getDiv() to
586
			// generate the whole field, label and errors and all, then wrap it in a Widget.
587
			// It might look weird, but it'll work OK.
588
			return $this->getFieldLayoutOOUI(
589
				new OOUI\Widget( [ 'content' => new OOUI\HtmlSnippet( $this->getDiv( $value ) ) ] ),
590
				[ 'infusable' => false, 'align' => 'top' ]
591
			);
592
		}
593
594
		$infusable = true;
595
		if ( is_string( $inputField ) ) {
596
			// We have an OOUI implementation, but it's not proper, and we got a load of HTML.
597
			// Cheat a little and wrap it in a widget. It won't be infusable, though, since client-side
598
			// JavaScript doesn't know how to rebuilt the contents.
599
			$inputField = new OOUI\Widget( [ 'content' => new OOUI\HtmlSnippet( $inputField ) ] );
600
			$infusable = false;
601
		}
602
603
		$fieldType = get_class( $this );
604
		$helpText = $this->getHelpText();
605
		$errors = $this->getErrorsRaw( $value );
606
		foreach ( $errors as &$error ) {
607
			$error = new OOUI\HtmlSnippet( $error );
608
		}
609
610
		$config = [
611
			'classes' => [ "mw-htmlform-field-$fieldType", $this->mClass ],
612
			'align' => $this->getLabelAlignOOUI(),
613
			'label' => new OOUI\HtmlSnippet( $this->getLabel() ),
614
			'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 604 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...
615
			'errors' => $errors,
616
			'infusable' => $infusable,
617
		];
618
619
		return $this->getFieldLayoutOOUI( $inputField, $config );
620
	}
621
622
	/**
623
	 * Get label alignment when generating field for OOUI.
624
	 * @return string 'left', 'right', 'top' or 'inline'
625
	 */
626
	protected function getLabelAlignOOUI() {
627
		return 'top';
628
	}
629
630
	/**
631
	 * Get a FieldLayout (or subclass thereof) to wrap this field in when using OOUI output.
632
	 * @return OOUI\FieldLayout|OOUI\ActionFieldLayout
633
	 */
634
	protected function getFieldLayoutOOUI( $inputField, $config ) {
635
		if ( isset( $this->mClassWithButton ) ) {
636
			$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...
637
			return new OOUI\ActionFieldLayout( $inputField, $buttonWidget, $config );
638
		}
639
		return new OOUI\FieldLayout( $inputField, $config );
640
	}
641
642
	/**
643
	 * Get the complete raw fields for the input, including help text,
644
	 * labels, and whatever.
645
	 * @since 1.20
646
	 *
647
	 * @param string $value The value to set the input to.
648
	 *
649
	 * @return string Complete HTML table row.
650
	 */
651
	public function getRaw( $value ) {
652
		list( $errors, ) = $this->getErrorsAndErrorClass( $value );
653
		$inputHtml = $this->getInputHTML( $value );
654
		$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...
655
		$cellAttributes = [];
656
		$label = $this->getLabelHtml( $cellAttributes );
657
658
		$html = "\n$errors";
659
		$html .= $label;
660
		$html .= $inputHtml;
661
		$html .= $helptext;
662
663
		return $html;
664
	}
665
666
	/**
667
	 * Get the complete field for the input, including help text,
668
	 * labels, and whatever. Fall back from 'vform' to 'div' when not overridden.
669
	 *
670
	 * @since 1.25
671
	 * @param string $value The value to set the input to.
672
	 * @return string Complete HTML field.
673
	 */
674
	public function getVForm( $value ) {
675
		// Ewwww
676
		$this->mVFormClass = ' mw-ui-vform-field';
677
		return $this->getDiv( $value );
678
	}
679
680
	/**
681
	 * Get the complete field as an inline element.
682
	 * @since 1.25
683
	 * @param string $value The value to set the input to.
684
	 * @return string Complete HTML inline element
685
	 */
686
	public function getInline( $value ) {
687
		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...
688
		$inputHtml = $this->getInputHTML( $value );
689
		$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...
690
		$cellAttributes = [];
691
		$label = $this->getLabelHtml( $cellAttributes );
692
693
		$html = "\n" . $errors .
694
			$label . '&#160;' .
695
			$inputHtml .
696
			$helptext;
697
698
		return $html;
699
	}
700
701
	/**
702
	 * Generate help text HTML in table format
703
	 * @since 1.20
704
	 *
705
	 * @param string|null $helptext
706
	 * @return string
707
	 */
708
	public function getHelpTextHtmlTable( $helptext ) {
709
		if ( is_null( $helptext ) ) {
710
			return '';
711
		}
712
713
		$rowAttributes = [];
714 View Code Duplication
		if ( $this->mHideIf ) {
715
			$rowAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
716
			$rowAttributes['class'] = 'mw-htmlform-hide-if';
717
		}
718
719
		$tdClasses = [ 'htmlform-tip' ];
720
		if ( $this->mHelpClass !== false ) {
721
			$tdClasses[] = $this->mHelpClass;
722
		}
723
		$row = Html::rawElement( 'td', [ 'colspan' => 2, 'class' => $tdClasses ], $helptext );
724
		$row = Html::rawElement( 'tr', $rowAttributes, $row );
725
726
		return $row;
727
	}
728
729
	/**
730
	 * Generate help text HTML in div format
731
	 * @since 1.20
732
	 *
733
	 * @param string|null $helptext
734
	 *
735
	 * @return string
736
	 */
737
	public function getHelpTextHtmlDiv( $helptext ) {
738
		if ( is_null( $helptext ) ) {
739
			return '';
740
		}
741
742
		$wrapperAttributes = [
743
			'class' => 'htmlform-tip',
744
		];
745
		if ( $this->mHelpClass !== false ) {
746
			$wrapperAttributes['class'] .= " {$this->mHelpClass}";
747
		}
748 View Code Duplication
		if ( $this->mHideIf ) {
749
			$wrapperAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
750
			$wrapperAttributes['class'] .= ' mw-htmlform-hide-if';
751
		}
752
		$div = Html::rawElement( 'div', $wrapperAttributes, $helptext );
753
754
		return $div;
755
	}
756
757
	/**
758
	 * Generate help text HTML formatted for raw output
759
	 * @since 1.20
760
	 *
761
	 * @param string|null $helptext
762
	 * @return string
763
	 */
764
	public function getHelpTextHtmlRaw( $helptext ) {
765
		return $this->getHelpTextHtmlDiv( $helptext );
766
	}
767
768
	/**
769
	 * Determine the help text to display
770
	 * @since 1.20
771
	 * @return string HTML
772
	 */
773
	public function getHelpText() {
774
		$helptext = null;
775
776
		if ( isset( $this->mParams['help-message'] ) ) {
777
			$this->mParams['help-messages'] = [ $this->mParams['help-message'] ];
778
		}
779
780
		if ( isset( $this->mParams['help-messages'] ) ) {
781
			foreach ( $this->mParams['help-messages'] as $name ) {
782
				$helpMessage = (array)$name;
783
				$msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
784
785
				if ( $msg->exists() ) {
786
					if ( is_null( $helptext ) ) {
787
						$helptext = '';
788
					} else {
789
						$helptext .= $this->msg( 'word-separator' )->escaped(); // some space
790
					}
791
					$helptext .= $msg->parse(); // Append message
792
				}
793
			}
794
		} elseif ( isset( $this->mParams['help'] ) ) {
795
			$helptext = $this->mParams['help'];
796
		}
797
798
		return $helptext;
799
	}
800
801
	/**
802
	 * Determine form errors to display and their classes
803
	 * @since 1.20
804
	 *
805
	 * @param string $value The value of the input
806
	 * @return array array( $errors, $errorClass )
807
	 */
808
	public function getErrorsAndErrorClass( $value ) {
809
		$errors = $this->validate( $value, $this->mParent->mFieldData );
810
811
		if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
812
			$errors = '';
813
			$errorClass = '';
814
		} else {
815
			$errors = self::formatErrors( $errors );
816
			$errorClass = 'mw-htmlform-invalid-input';
817
		}
818
819
		return [ $errors, $errorClass ];
820
	}
821
822
	/**
823
	 * Determine form errors to display, returning them in an array.
824
	 *
825
	 * @since 1.26
826
	 * @param string $value The value of the input
827
	 * @return string[] Array of error HTML strings
828
	 */
829
	public function getErrorsRaw( $value ) {
830
		$errors = $this->validate( $value, $this->mParent->mFieldData );
831
832
		if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
833
			$errors = [];
834
		}
835
836
		if ( !is_array( $errors ) ) {
837
			$errors = [ $errors ];
838
		}
839
		foreach ( $errors as &$error ) {
840
			if ( $error instanceof Message ) {
841
				$error = $error->parse();
842
			}
843
		}
844
845
		return $errors;
846
	}
847
848
	/**
849
	 * @return string HTML
850
	 */
851
	function getLabel() {
852
		return is_null( $this->mLabel ) ? '' : $this->mLabel;
853
	}
854
855
	function getLabelHtml( $cellAttributes = [] ) {
856
		# Don't output a for= attribute for labels with no associated input.
857
		# Kind of hacky here, possibly we don't want these to be <label>s at all.
858
		$for = [];
859
860
		if ( $this->needsLabel() ) {
861
			$for['for'] = $this->mID;
862
		}
863
864
		$labelValue = trim( $this->getLabel() );
865
		$hasLabel = false;
866
		if ( $labelValue !== '&#160;' && $labelValue !== '' ) {
867
			$hasLabel = true;
868
		}
869
870
		$displayFormat = $this->mParent->getDisplayFormat();
871
		$html = '';
872
		$horizontalLabel = isset( $this->mParams['horizontal-label'] )
873
			? $this->mParams['horizontal-label'] : false;
874
875
		if ( $displayFormat === 'table' ) {
876
			$html =
877
				Html::rawElement( 'td',
878
					[ 'class' => 'mw-label' ] + $cellAttributes,
879
					Html::rawElement( 'label', $for, $labelValue ) );
880
		} elseif ( $hasLabel || $this->mShowEmptyLabels ) {
881
			if ( $displayFormat === 'div' && !$horizontalLabel ) {
882
				$html =
883
					Html::rawElement( 'div',
884
						[ 'class' => 'mw-label' ] + $cellAttributes,
885
						Html::rawElement( 'label', $for, $labelValue ) );
886
			} else {
887
				$html = Html::rawElement( 'label', $for, $labelValue );
888
			}
889
		}
890
891
		return $html;
892
	}
893
894
	function getDefault() {
895
		if ( isset( $this->mDefault ) ) {
896
			return $this->mDefault;
897
		} else {
898
			return null;
899
		}
900
	}
901
902
	/**
903
	 * Returns the attributes required for the tooltip and accesskey.
904
	 *
905
	 * @return array Attributes
906
	 */
907
	public function getTooltipAndAccessKey() {
908
		if ( empty( $this->mParams['tooltip'] ) ) {
909
			return [];
910
		}
911
912
		return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
913
	}
914
915
	/**
916
	 * Returns the given attributes from the parameters
917
	 *
918
	 * @param array $list List of attributes to get
919
	 * @return array Attributes
920
	 */
921
	public function getAttributes( array $list ) {
922
		static $boolAttribs = [ 'disabled', 'required', 'autofocus', 'multiple', 'readonly' ];
923
924
		$ret = [];
925
		foreach ( $list as $key ) {
926
			if ( in_array( $key, $boolAttribs ) ) {
927
				if ( !empty( $this->mParams[$key] ) ) {
928
					$ret[$key] = '';
929
				}
930
			} elseif ( isset( $this->mParams[$key] ) ) {
931
				$ret[$key] = $this->mParams[$key];
932
			}
933
		}
934
935
		return $ret;
936
	}
937
938
	/**
939
	 * Given an array of msg-key => value mappings, returns an array with keys
940
	 * being the message texts. It also forces values to strings.
941
	 *
942
	 * @param array $options
943
	 * @return array
944
	 */
945
	private function lookupOptionsKeys( $options ) {
946
		$ret = [];
947
		foreach ( $options as $key => $value ) {
948
			$key = $this->msg( $key )->plain();
949
			$ret[$key] = is_array( $value )
950
				? $this->lookupOptionsKeys( $value )
951
				: strval( $value );
952
		}
953
		return $ret;
954
	}
955
956
	/**
957
	 * Recursively forces values in an array to strings, because issues arise
958
	 * with integer 0 as a value.
959
	 *
960
	 * @param array $array
961
	 * @return array
962
	 */
963
	static function forceToStringRecursive( $array ) {
964
		if ( is_array( $array ) ) {
965
			return array_map( [ __CLASS__, 'forceToStringRecursive' ], $array );
966
		} else {
967
			return strval( $array );
968
		}
969
	}
970
971
	/**
972
	 * Fetch the array of options from the field's parameters. In order, this
973
	 * checks 'options-messages', 'options', then 'options-message'.
974
	 *
975
	 * @return array|null Options array
976
	 */
977
	public function getOptions() {
978
		if ( $this->mOptions === false ) {
979
			if ( array_key_exists( 'options-messages', $this->mParams ) ) {
980
				$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...
981
			} elseif ( array_key_exists( 'options', $this->mParams ) ) {
982
				$this->mOptionsLabelsNotFromMessage = true;
983
				$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...
984
			} elseif ( array_key_exists( 'options-message', $this->mParams ) ) {
985
				/** @todo This is copied from Xml::listDropDown(), deprecate/avoid duplication? */
986
				$message = $this->msg( $this->mParams['options-message'] )->inContentLanguage()->plain();
987
988
				$optgroup = false;
989
				$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...
990
				foreach ( explode( "\n", $message ) as $option ) {
991
					$value = trim( $option );
992
					if ( $value == '' ) {
993
						continue;
994
					} elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
995
						# A new group is starting...
996
						$value = trim( substr( $value, 1 ) );
997
						$optgroup = $value;
998
					} elseif ( substr( $value, 0, 2 ) == '**' ) {
999
						# groupmember
1000
						$opt = trim( substr( $value, 2 ) );
1001
						if ( $optgroup === false ) {
1002
							$this->mOptions[$opt] = $opt;
1003
						} else {
1004
							$this->mOptions[$optgroup][$opt] = $opt;
1005
						}
1006
					} else {
1007
						# groupless reason list
1008
						$optgroup = false;
1009
						$this->mOptions[$option] = $option;
1010
					}
1011
				}
1012
			} else {
1013
				$this->mOptions = null;
1014
			}
1015
		}
1016
1017
		return $this->mOptions;
1018
	}
1019
1020
	/**
1021
	 * Get options and make them into arrays suitable for OOUI.
1022
	 * @return array Options for inclusion in a select or whatever.
1023
	 */
1024
	public function getOptionsOOUI() {
1025
		$oldoptions = $this->getOptions();
1026
1027
		if ( $oldoptions === null ) {
1028
			return null;
1029
		}
1030
1031
		$options = [];
1032
1033
		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...
1034
			$options[] = [
1035
				'data' => (string)$data,
1036
				'label' => (string)$text,
1037
			];
1038
		}
1039
1040
		return $options;
1041
	}
1042
1043
	/**
1044
	 * flatten an array of options to a single array, for instance,
1045
	 * a set of "<options>" inside "<optgroups>".
1046
	 *
1047
	 * @param array $options Associative Array with values either Strings or Arrays
1048
	 * @return array Flattened input
1049
	 */
1050
	public static function flattenOptions( $options ) {
1051
		$flatOpts = [];
1052
1053
		foreach ( $options as $value ) {
1054
			if ( is_array( $value ) ) {
1055
				$flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1056
			} else {
1057
				$flatOpts[] = $value;
1058
			}
1059
		}
1060
1061
		return $flatOpts;
1062
	}
1063
1064
	/**
1065
	 * Formats one or more errors as accepted by field validation-callback.
1066
	 *
1067
	 * @param string|Message|array $errors Array of strings or Message instances
1068
	 * @return string HTML
1069
	 * @since 1.18
1070
	 */
1071
	protected static function formatErrors( $errors ) {
1072
		if ( is_array( $errors ) && count( $errors ) === 1 ) {
1073
			$errors = array_shift( $errors );
1074
		}
1075
1076
		if ( is_array( $errors ) ) {
1077
			$lines = [];
1078
			foreach ( $errors as $error ) {
1079
				if ( $error instanceof Message ) {
1080
					$lines[] = Html::rawElement( 'li', [], $error->parse() );
1081
				} else {
1082
					$lines[] = Html::rawElement( 'li', [], $error );
1083
				}
1084
			}
1085
1086
			return Html::rawElement( 'ul', [ 'class' => 'error' ], implode( "\n", $lines ) );
1087
		} else {
1088
			if ( $errors instanceof Message ) {
1089
				$errors = $errors->parse();
1090
			}
1091
1092
			return Html::rawElement( 'span', [ 'class' => 'error' ], $errors );
1093
		}
1094
	}
1095
}
1096