Merge "Special:Upload should not crash on failing previews"
[mediawiki.git] / includes / FormOptions.php
blob725a512980937c3b51c1c400711165e797526ce6
1 <?php
2 /**
3 * Helper class to keep track of options when mixing links and form elements.
5 * Copyright © 2008, Niklas Laxström
6 * Copyright © 2011, Antoine Musso
7 * Copyright © 2013, Bartosz Dziewoński
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.
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.
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
24 * @file
25 * @author Niklas Laxström
26 * @author Antoine Musso
29 /**
30 * Helper class to keep track of options when mixing links and form elements.
32 * @todo This badly needs some examples and tests :) The usage in SpecialRecentchanges class is a
33 * good ersatz in the meantime.
35 class FormOptions implements ArrayAccess {
36 /** @name Type constants
37 * Used internally to map an option value to a WebRequest accessor
39 /* @{ */
40 /** Mark value for automatic detection (for simple data types only) */
41 const AUTO = -1;
42 /** String type, maps guessType() to WebRequest::getText() */
43 const STRING = 0;
44 /** Integer type, maps guessType() to WebRequest::getInt() */
45 const INT = 1;
46 /** Float type, maps guessType() to WebRequest::getFloat()
47 * @since 1.23 */
48 const FLOAT = 4;
49 /** Boolean type, maps guessType() to WebRequest::getBool() */
50 const BOOL = 2;
51 /** Integer type or null, maps to WebRequest::getIntOrNull()
52 * This is useful for the namespace selector.
54 const INTNULL = 3;
55 /** Array type, maps guessType() to WebRequest::getArray()
56 * @since 1.29 */
57 const ARR = 5;
58 /* @} */
60 /**
61 * Map of known option names to information about them.
63 * Each value is an array with the following keys:
64 * - 'default' - the default value as passed to add()
65 * - 'value' - current value, start with null, can be set by various functions
66 * - 'consumed' - true/false, whether the option was consumed using
67 * consumeValue() or consumeValues()
68 * - 'type' - one of the type constants (but never AUTO)
70 protected $options = [];
72 # Setting up
74 /**
75 * Add an option to be handled by this FormOptions instance.
77 * @param string $name Request parameter name
78 * @param mixed $default Default value when the request parameter is not present
79 * @param int $type One of the type constants (optional, defaults to AUTO)
81 public function add( $name, $default, $type = self::AUTO ) {
82 $option = [];
83 $option['default'] = $default;
84 $option['value'] = null;
85 $option['consumed'] = false;
87 if ( $type !== self::AUTO ) {
88 $option['type'] = $type;
89 } else {
90 $option['type'] = self::guessType( $default );
93 $this->options[$name] = $option;
96 /**
97 * Remove an option being handled by this FormOptions instance. This is the inverse of add().
99 * @param string $name Request parameter name
101 public function delete( $name ) {
102 $this->validateName( $name, true );
103 unset( $this->options[$name] );
107 * Used to find out which type the data is. All types are defined in the 'Type constants' section
108 * of this class.
110 * Detection of the INTNULL type is not supported; INT will be assumed if the data is an integer,
111 * MWException will be thrown if it's null.
113 * @param mixed $data Value to guess the type for
114 * @throws MWException If unable to guess the type
115 * @return int Type constant
117 public static function guessType( $data ) {
118 if ( is_bool( $data ) ) {
119 return self::BOOL;
120 } elseif ( is_int( $data ) ) {
121 return self::INT;
122 } elseif ( is_float( $data ) ) {
123 return self::FLOAT;
124 } elseif ( is_string( $data ) ) {
125 return self::STRING;
126 } elseif ( is_array( $data ) ) {
127 return self::ARR;
128 } else {
129 throw new MWException( 'Unsupported datatype' );
133 # Handling values
136 * Verify that the given option name exists.
138 * @param string $name Option name
139 * @param bool $strict Throw an exception when the option doesn't exist instead of returning false
140 * @throws MWException
141 * @return bool True if the option exists, false otherwise
143 public function validateName( $name, $strict = false ) {
144 if ( !isset( $this->options[$name] ) ) {
145 if ( $strict ) {
146 throw new MWException( "Invalid option $name" );
147 } else {
148 return false;
152 return true;
156 * Use to set the value of an option.
158 * @param string $name Option name
159 * @param mixed $value Value for the option
160 * @param bool $force Whether to set the value when it is equivalent to the default value for this
161 * option (default false).
163 public function setValue( $name, $value, $force = false ) {
164 $this->validateName( $name, true );
166 if ( !$force && $value === $this->options[$name]['default'] ) {
167 // null default values as unchanged
168 $this->options[$name]['value'] = null;
169 } else {
170 $this->options[$name]['value'] = $value;
175 * Get the value for the given option name. Uses getValueReal() internally.
177 * @param string $name Option name
178 * @return mixed
180 public function getValue( $name ) {
181 $this->validateName( $name, true );
183 return $this->getValueReal( $this->options[$name] );
187 * Return current option value, based on a structure taken from $options.
189 * @param array $option Array structure describing the option
190 * @return mixed Value, or the default value if it is null
192 protected function getValueReal( $option ) {
193 if ( $option['value'] !== null ) {
194 return $option['value'];
195 } else {
196 return $option['default'];
201 * Delete the option value.
202 * This will make future calls to getValue() return the default value.
203 * @param string $name Option name
205 public function reset( $name ) {
206 $this->validateName( $name, true );
207 $this->options[$name]['value'] = null;
211 * Get the value of given option and mark it as 'consumed'. Consumed options are not returned
212 * by getUnconsumedValues().
214 * @see consumeValues()
215 * @throws MWException If the option does not exist
216 * @param string $name Option name
217 * @return mixed Value, or the default value if it is null
219 public function consumeValue( $name ) {
220 $this->validateName( $name, true );
221 $this->options[$name]['consumed'] = true;
223 return $this->getValueReal( $this->options[$name] );
227 * Get the values of given options and mark them as 'consumed'. Consumed options are not returned
228 * by getUnconsumedValues().
230 * @see consumeValue()
231 * @throws MWException If any option does not exist
232 * @param array $names Array of option names as strings
233 * @return array Array of option values, or the default values if they are null
235 public function consumeValues( $names ) {
236 $out = [];
238 foreach ( $names as $name ) {
239 $this->validateName( $name, true );
240 $this->options[$name]['consumed'] = true;
241 $out[] = $this->getValueReal( $this->options[$name] );
244 return $out;
248 * @see validateBounds()
250 public function validateIntBounds( $name, $min, $max ) {
251 $this->validateBounds( $name, $min, $max );
255 * Constrain a numeric value for a given option to a given range. The value will be altered to fit
256 * in the range.
258 * @since 1.23
260 * @param string $name Option name
261 * @param int|float $min Minimum value
262 * @param int|float $max Maximum value
263 * @throws MWException If option is not of type INT
265 public function validateBounds( $name, $min, $max ) {
266 $this->validateName( $name, true );
267 $type = $this->options[$name]['type'];
269 if ( $type !== self::INT && $type !== self::FLOAT ) {
270 throw new MWException( "Option $name is not of type INT or FLOAT" );
273 $value = $this->getValueReal( $this->options[$name] );
274 $value = max( $min, min( $max, $value ) );
276 $this->setValue( $name, $value );
280 * Get all remaining values which have not been consumed by consumeValue() or consumeValues().
282 * @param bool $all Whether to include unchanged options (default: false)
283 * @return array
285 public function getUnconsumedValues( $all = false ) {
286 $values = [];
288 foreach ( $this->options as $name => $data ) {
289 if ( !$data['consumed'] ) {
290 if ( $all || $data['value'] !== null ) {
291 $values[$name] = $this->getValueReal( $data );
296 return $values;
300 * Return options modified as an array ( name => value )
301 * @return array
303 public function getChangedValues() {
304 $values = [];
306 foreach ( $this->options as $name => $data ) {
307 if ( $data['value'] !== null ) {
308 $values[$name] = $data['value'];
312 return $values;
316 * Format options to an array ( name => value )
317 * @return array
319 public function getAllValues() {
320 $values = [];
322 foreach ( $this->options as $name => $data ) {
323 $values[$name] = $this->getValueReal( $data );
326 return $values;
329 # Reading values
332 * Fetch values for all options (or selected options) from the given WebRequest, making them
333 * available for accessing with getValue() or consumeValue() etc.
335 * @param WebRequest $r The request to fetch values from
336 * @param array $optionKeys Which options to fetch the values for (default:
337 * all of them). Note that passing an empty array will also result in
338 * values for all keys being fetched.
339 * @throws MWException If the type of any option is invalid
341 public function fetchValuesFromRequest( WebRequest $r, $optionKeys = null ) {
342 if ( !$optionKeys ) {
343 $optionKeys = array_keys( $this->options );
346 foreach ( $optionKeys as $name ) {
347 $default = $this->options[$name]['default'];
348 $type = $this->options[$name]['type'];
350 switch ( $type ) {
351 case self::BOOL:
352 $value = $r->getBool( $name, $default );
353 break;
354 case self::INT:
355 $value = $r->getInt( $name, $default );
356 break;
357 case self::FLOAT:
358 $value = $r->getFloat( $name, $default );
359 break;
360 case self::STRING:
361 $value = $r->getText( $name, $default );
362 break;
363 case self::INTNULL:
364 $value = $r->getIntOrNull( $name );
365 break;
366 case self::ARR:
367 $value = $r->getArray( $name );
368 break;
369 default:
370 throw new MWException( 'Unsupported datatype' );
373 if ( $value !== null ) {
374 $this->options[$name]['value'] = $value === $default ? null : $value;
379 /** @name ArrayAccess functions
380 * These functions implement the ArrayAccess PHP interface.
381 * @see https://secure.php.net/manual/en/class.arrayaccess.php
383 /* @{ */
385 * Whether the option exists.
386 * @param string $name
387 * @return bool
389 public function offsetExists( $name ) {
390 return isset( $this->options[$name] );
394 * Retrieve an option value.
395 * @param string $name
396 * @return mixed
398 public function offsetGet( $name ) {
399 return $this->getValue( $name );
403 * Set an option to given value.
404 * @param string $name
405 * @param mixed $value
407 public function offsetSet( $name, $value ) {
408 $this->setValue( $name, $value );
412 * Delete the option.
413 * @param string $name
415 public function offsetUnset( $name ) {
416 $this->delete( $name );
418 /* @} */