Debian Codegraph @

includes/Html/FormOptions.php

raw symbols SCIP
1 <?php
2 /**
3 * Helper class to keep track of options when mixing links and form elements.
4 *
5 * Copyright © 2008, Niklas Laxström
6 * Copyright © 2011, Antoine Musso
7 * Copyright © 2013, Bartosz Dziewoński
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 * @author Niklas Laxström
26 * @author Antoine Musso
27 */
28
29 namespace MediaWiki\Html;
30
31 use ArrayAccess;
32 use InvalidArgumentException;
33 use MediaWiki\Request\WebRequest;
34 use UnexpectedValueException;
35
36 /**
37 * Helper class to keep track of options when mixing links and form elements.
38 *
39 * @todo This badly needs some examples and tests :) The usage in SpecialRecentchanges class is a
40 * good ersatz in the meantime.
41 */
42 class FormOptions implements ArrayAccess {
43 /** @name Type constants
44 * Used internally to map an option value to a WebRequest accessor
45 * @{
46 */
47 /** Mark value for automatic detection (for simple data types only) */
48 public const AUTO = -1;
49 /** String type, maps guessType() to WebRequest::getText() */
50 public const STRING = 0;
51 /** Integer type, maps guessType() to WebRequest::getInt() */
52 public const INT = 1;
53 /** Float type, maps guessType() to WebRequest::getFloat()
54 * @since 1.23
55 */
56 public const FLOAT = 4;
57 /** Boolean type, maps guessType() to WebRequest::getBool() */
58 public const BOOL = 2;
59 /** Integer type or null, maps to WebRequest::getIntOrNull()
60 * This is useful for the namespace selector.
61 */
62 public const INTNULL = 3;
63 /** Array type, maps guessType() to WebRequest::getArray()
64 * @since 1.29
65 */
66 public const ARR = 5;
67 /** @} */
68
69 /**
70 * Map of known option names to information about them.
71 *
72 * Each value is an array with the following keys:
73 * - 'default' - the default value as passed to add()
74 * - 'value' - current value, start with null, can be set by various functions
75 * - 'consumed' - true/false, whether the option was consumed using
76 * consumeValue() or consumeValues()
77 * - 'type' - one of the type constants (but never AUTO)
78 * @var array
79 */
80 protected $options = [];
81
82 # Setting up
83
84 /**
85 * Add an option to be handled by this FormOptions instance.
86 *
87 * @param string $name Request parameter name
88 * @param mixed $default Default value when the request parameter is not present
89 * @param int $type One of the type constants (optional, defaults to AUTO)
90 */
91 public function add( $name, $default, $type = self::AUTO ) {
92 $option = [];
93 $option['default'] = $default;
94 $option['value'] = null;
95 $option['consumed'] = false;
96
97 if ( $type !== self::AUTO ) {
98 $option['type'] = $type;
99 } else {
100 $option['type'] = self::guessType( $default );
101 }
102
103 $this->options[$name] = $option;
104 }
105
106 /**
107 * Remove an option being handled by this FormOptions instance. This is the inverse of add().
108 *
109 * @param string $name Request parameter name
110 */
111 public function delete( $name ) {
112 $this->validateName( $name, true );
113 unset( $this->options[$name] );
114 }
115
116 /**
117 * Used to find out which type the data is. All types are defined in the 'Type constants' section
118 * of this class.
119 *
120 * Detection of the INTNULL type is not supported; INT will be assumed if the data is an integer.
121 *
122 * @param mixed $data Value to guess the type for
123 * @return int Type constant
124 */
125 public static function guessType( $data ) {
126 if ( is_bool( $data ) ) {
127 return self::BOOL;
128 } elseif ( is_int( $data ) ) {
129 return self::INT;
130 } elseif ( is_float( $data ) ) {
131 return self::FLOAT;
132 } elseif ( is_string( $data ) ) {
133 return self::STRING;
134 } elseif ( is_array( $data ) ) {
135 return self::ARR;
136 } else {
137 throw new InvalidArgumentException( 'Unsupported datatype' );
138 }
139 }
140
141 # Handling values
142
143 /**
144 * Verify that the given option name exists.
145 *
146 * @param string $name Option name
147 * @param bool $strict Throw an exception when the option doesn't exist instead of returning false
148 * @return bool True if the option exists, false otherwise
149 */
150 public function validateName( $name, $strict = false ) {
151 if ( !isset( $this->options[$name] ) ) {
152 if ( $strict ) {
153 throw new InvalidArgumentException( "Invalid option $name" );
154 } else {
155 return false;
156 }
157 }
158
159 return true;
160 }
161
162 /**
163 * Use to set the value of an option.
164 *
165 * @param string $name Option name
166 * @param mixed $value Value for the option
167 * @param bool $force Whether to set the value when it is equivalent to the default value for this
168 * option (default false).
169 */
170 public function setValue( $name, $value, $force = false ) {
171 $this->validateName( $name, true );
172
173 if ( !$force && $value === $this->options[$name]['default'] ) {
174 // null default values as unchanged
175 $this->options[$name]['value'] = null;
176 } else {
177 $this->options[$name]['value'] = $value;
178 }
179 }
180
181 /**
182 * Get the value for the given option name. Uses getValueReal() internally.
183 *
184 * @param string $name Option name
185 * @return mixed
186 * @return-taint tainted This actually depends on the type of the option, but there's no way to determine that
187 * statically.
188 */
189 public function getValue( $name ) {
190 $this->validateName( $name, true );
191
192 return $this->getValueReal( $this->options[$name] );
193 }
194
195 /**
196 * Return current option value, based on a structure taken from $options.
197 *
198 * @param array $option Array structure describing the option
199 * @return mixed Value, or the default value if it is null
200 */
201 protected function getValueReal( $option ) {
202 if ( $option['value'] !== null ) {
203 return $option['value'];
204 } else {
205 return $option['default'];
206 }
207 }
208
209 /**
210 * Delete the option value.
211 * This will make future calls to getValue() return the default value.
212 * @param string $name Option name
213 */
214 public function reset( $name ) {
215 $this->validateName( $name, true );
216 $this->options[$name]['value'] = null;
217 }
218
219 /**
220 * Get the value of given option and mark it as 'consumed'. Consumed options are not returned
221 * by getUnconsumedValues(). Callers should verify that the given option exists.
222 *
223 * @see consumeValues()
224 * @param string $name Option name
225 * @return mixed Value, or the default value if it is null
226 */
227 public function consumeValue( $name ) {
228 $this->validateName( $name, true );
229 $this->options[$name]['consumed'] = true;
230
231 return $this->getValueReal( $this->options[$name] );
232 }
233
234 /**
235 * Get the values of given options and mark them as 'consumed'. Consumed options are not returned
236 * by getUnconsumedValues(). Callers should verify that all the given options exist.
237 *
238 * @see consumeValue()
239 * @param string[] $names List of option names
240 * @return array Array of option values, or the default values if they are null
241 */
242 public function consumeValues( $names ) {
243 $out = [];
244
245 foreach ( $names as $name ) {
246 $this->validateName( $name, true );
247 $this->options[$name]['consumed'] = true;
248 $out[] = $this->getValueReal( $this->options[$name] );
249 }
250
251 return $out;
252 }
253
254 /**
255 * @see validateBounds()
256 * @param string $name
257 * @param int $min
258 * @param int $max
259 */
260 public function validateIntBounds( $name, $min, $max ) {
261 $this->validateBounds( $name, $min, $max );
262 }
263
264 /**
265 * Constrain a numeric value for a given option to a given range. The value will be altered to fit
266 * in the range.
267 *
268 * @since 1.23
269 *
270 * @param string $name Option name. Must be of numeric type.
271 * @param int|float $min Minimum value
272 * @param int|float $max Maximum value
273 */
274 public function validateBounds( $name, $min, $max ) {
275 $this->validateName( $name, true );
276 $type = $this->options[$name]['type'];
277
278 if ( $type !== self::INT && $type !== self::INTNULL && $type !== self::FLOAT ) {
279 throw new InvalidArgumentException( "Type of option $name is not numeric" );
280 }
281
282 $value = $this->getValueReal( $this->options[$name] );
283 if ( $type !== self::INTNULL || $value !== null ) {
284 $this->setValue( $name, max( $min, min( $max, $value ) ) );
285 }
286 }
287
288 /**
289 * Get all remaining values which have not been consumed by consumeValue() or consumeValues().
290 *
291 * @param bool $all Whether to include unchanged options (default: false)
292 * @return array
293 */
294 public function getUnconsumedValues( $all = false ) {
295 $values = [];
296
297 foreach ( $this->options as $name => $data ) {
298 if ( !$data['consumed'] ) {
299 if ( $all || $data['value'] !== null ) {
300 $values[$name] = $this->getValueReal( $data );
301 }
302 }
303 }
304
305 return $values;
306 }
307
308 /**
309 * Return options modified as an array ( name => value )
310 * @return array
311 */
312 public function getChangedValues() {
313 $values = [];
314
315 foreach ( $this->options as $name => $data ) {
316 if ( $data['value'] !== null ) {
317 $values[$name] = $data['value'];
318 }
319 }
320
321 return $values;
322 }
323
324 /**
325 * Format options to an array ( name => value )
326 * @return array
327 */
328 public function getAllValues() {
329 $values = [];
330
331 foreach ( $this->options as $name => $data ) {
332 $values[$name] = $this->getValueReal( $data );
333 }
334
335 return $values;
336 }
337
338 # Reading values
339
340 /**
341 * Fetch values for all options (or selected options) from the given WebRequest, making them
342 * available for accessing with getValue() or consumeValue() etc.
343 *
344 * @param WebRequest $r The request to fetch values from
345 * @param array|null $optionKeys Which options to fetch the values for (default:
346 * all of them). Note that passing an empty array will also result in
347 * values for all keys being fetched.
348 */
349 public function fetchValuesFromRequest( WebRequest $r, $optionKeys = null ) {
350 if ( !$optionKeys ) {
351 $optionKeys = array_keys( $this->options );
352 }
353
354 foreach ( $optionKeys as $name ) {
355 $default = $this->options[$name]['default'];
356 $type = $this->options[$name]['type'];
357
358 switch ( $type ) {
359 case self::BOOL:
360 $value = $r->getBool( $name, $default );
361 break;
362 case self::INT:
363 $value = $r->getInt( $name, $default );
364 break;
365 case self::FLOAT:
366 $value = $r->getFloat( $name, $default );
367 break;
368 case self::STRING:
369 $value = $r->getText( $name, $default );
370 break;
371 case self::INTNULL:
372 $value = $r->getIntOrNull( $name );
373 break;
374 case self::ARR:
375 $value = $r->getArray( $name );
376
377 if ( $value !== null ) {
378 // Reject nested arrays (T344931)
379 $value = array_filter( $value, 'is_scalar' );
380 }
381 break;
382 default:
383 throw new UnexpectedValueException( "Unsupported datatype $type" );
384 }
385
386 if ( $value !== null ) {
387 $this->options[$name]['value'] = $value === $default ? null : $value;
388 }
389 }
390 }
391
392 /***************************************************************************/
393 // region ArrayAccess functions
394 /** @name ArrayAccess functions
395 * These functions implement the ArrayAccess PHP interface.
396 * @see https://www.php.net/manual/en/class.arrayaccess.php
397 */
398
399 /**
400 * Whether the option exists.
401 * @param string $name
402 * @return bool
403 */
404 public function offsetExists( $name ): bool {
405 return isset( $this->options[$name] );
406 }
407
408 /**
409 * Retrieve an option value.
410 * @param string $name
411 * @return mixed
412 */
413 #[\ReturnTypeWillChange]
414 public function offsetGet( $name ) {
415 return $this->getValue( $name );
416 }
417
418 /**
419 * Set an option to given value.
420 * @param string $name
421 * @param mixed $value
422 */
423 public function offsetSet( $name, $value ): void {
424 $this->setValue( $name, $value );
425 }
426
427 /**
428 * Delete the option.
429 * @param string $name
430 */
431 public function offsetUnset( $name ): void {
432 $this->delete( $name );
433 }
434
435 // endregion -- end of ArrayAccess functions
436 }
437
438 /** @deprecated class alias since 1.40 */
439 class_alias( FormOptions::class, 'FormOptions' );