Refactor diffs
[mediawiki.git] / includes / FormOptions.php
blob54822e327187e74b45cddf0905f0c4d5be43ccea
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
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
23 * @file
24 * @author Niklas Laxström
25 * @author Antoine Musso
28 /**
29 * Helper class to keep track of options when mixing links and form elements.
31 * @todo This badly needs some examples and tests :) The usage in SpecialRecentchanges class is a
32 * good ersatz in the meantime.
34 class FormOptions implements ArrayAccess {
35 /** @name Type constants
36 * Used internally to map an option value to a WebRequest accessor
38 /* @{ */
39 /** Mark value for automatic detection (for simple data types only) */
40 const AUTO = -1;
41 /** String type, maps guessType() to WebRequest::getText() */
42 const STRING = 0;
43 /** Integer type, maps guessType() to WebRequest::getInt() */
44 const INT = 1;
45 /** Boolean type, maps guessType() to WebRequest::getBool() */
46 const BOOL = 2;
47 /** Integer type or null, maps to WebRequest::getIntOrNull()
48 * This is useful for the namespace selector.
50 const INTNULL = 3;
51 /* @} */
53 /**
54 * Map of known option names to information about them.
56 * Each value is an array with the following keys:
57 * - 'default' - the default value as passed to add()
58 * - 'value' - current value, start with null, can be set by various functions
59 * - 'consumed' - true/false, whether the option was consumed using
60 * consumeValue() or consumeValues()
61 * - 'type' - one of the type constants (but never AUTO)
63 protected $options = array();
65 # Setting up
67 /**
68 * Add an option to be handled by this FormOptions instance.
70 * @param string $name Request parameter name
71 * @param mixed $default Default value when the request parameter is not present
72 * @param int $type One of the type constants (optional, defaults to AUTO)
74 public function add( $name, $default, $type = self::AUTO ) {
75 $option = array();
76 $option['default'] = $default;
77 $option['value'] = null;
78 $option['consumed'] = false;
80 if ( $type !== self::AUTO ) {
81 $option['type'] = $type;
82 } else {
83 $option['type'] = self::guessType( $default );
86 $this->options[$name] = $option;
89 /**
90 * Remove an option being handled by this FormOptions instance. This is the inverse of add().
92 * @param string $name Request parameter name
94 public function delete( $name ) {
95 $this->validateName( $name, true );
96 unset( $this->options[$name] );
99 /**
100 * Used to find out which type the data is. All types are defined in the 'Type constants' section
101 * of this class.
103 * Detection of the INTNULL type is not supported; INT will be assumed if the data is an integer,
104 * MWException will be thrown if it's null.
106 * @param mixed $data Value to guess the type for
107 * @throws MWException If unable to guess the type
108 * @return int Type constant
110 public static function guessType( $data ) {
111 if ( is_bool( $data ) ) {
112 return self::BOOL;
113 } elseif ( is_int( $data ) ) {
114 return self::INT;
115 } elseif ( is_string( $data ) ) {
116 return self::STRING;
117 } else {
118 throw new MWException( 'Unsupported datatype' );
122 # Handling values
125 * Verify that the given option name exists.
127 * @param string $name Option name
128 * @param bool $strict Throw an exception when the option doesn't exist instead of returning false
129 * @throws MWException
130 * @return bool True if the option exists, false otherwise
132 public function validateName( $name, $strict = false ) {
133 if ( !isset( $this->options[$name] ) ) {
134 if ( $strict ) {
135 throw new MWException( "Invalid option $name" );
136 } else {
137 return false;
141 return true;
145 * Use to set the value of an option.
147 * @param string $name Option name
148 * @param mixed $value Value for the option
149 * @param bool $force Whether to set the value when it is equivalent to the default value for this
150 * option (default false).
152 public function setValue( $name, $value, $force = false ) {
153 $this->validateName( $name, true );
155 if ( !$force && $value === $this->options[$name]['default'] ) {
156 // null default values as unchanged
157 $this->options[$name]['value'] = null;
158 } else {
159 $this->options[$name]['value'] = $value;
164 * Get the value for the given option name. Uses getValueReal() internally.
166 * @param string $name Option name
167 * @return mixed
169 public function getValue( $name ) {
170 $this->validateName( $name, true );
172 return $this->getValueReal( $this->options[$name] );
176 * Return current option value, based on a structure taken from $options.
178 * @param array $option Array structure describing the option
179 * @return mixed Value, or the default value if it is null
181 protected function getValueReal( $option ) {
182 if ( $option['value'] !== null ) {
183 return $option['value'];
184 } else {
185 return $option['default'];
190 * Delete the option value.
191 * This will make future calls to getValue() return the default value.
192 * @param string $name Option name
194 public function reset( $name ) {
195 $this->validateName( $name, true );
196 $this->options[$name]['value'] = null;
200 * Get the value of given option and mark it as 'consumed'. Consumed options are not returned
201 * by getUnconsumedValues().
203 * @see consumeValues()
204 * @throws MWException If the option does not exist
205 * @param string $name Option name
206 * @return mixed Value, or the default value if it is null
208 public function consumeValue( $name ) {
209 $this->validateName( $name, true );
210 $this->options[$name]['consumed'] = true;
212 return $this->getValueReal( $this->options[$name] );
216 * Get the values of given options and mark them as 'consumed'. Consumed options are not returned
217 * by getUnconsumedValues().
219 * @see consumeValue()
220 * @throws MWException If any option does not exist
221 * @param array $names Array of option names as strings
222 * @return array Array of option values, or the default values if they are null
224 public function consumeValues( $names ) {
225 $out = array();
227 foreach ( $names as $name ) {
228 $this->validateName( $name, true );
229 $this->options[$name]['consumed'] = true;
230 $out[] = $this->getValueReal( $this->options[$name] );
233 return $out;
237 * Validate and set an option integer value
238 * The value will be altered to fit in the range.
240 * @param string $name option name
241 * @param int $min minimum value
242 * @param int $max maximum value
243 * @throws MWException If option is not of type INT
245 public function validateIntBounds( $name, $min, $max ) {
246 $this->validateName( $name, true );
248 if ( $this->options[$name]['type'] !== self::INT ) {
249 throw new MWException( "Option $name is not of type int" );
252 $value = $this->getValueReal( $this->options[$name] );
253 $value = max( $min, min( $max, $value ) );
255 $this->setValue( $name, $value );
259 * Get all remaining values which have not been consumed by consumeValue() or consumeValues().
261 * @param bool $all Whether to include unchanged options (default: false)
262 * @return array
264 public function getUnconsumedValues( $all = false ) {
265 $values = array();
267 foreach ( $this->options as $name => $data ) {
268 if ( !$data['consumed'] ) {
269 if ( $all || $data['value'] !== null ) {
270 $values[$name] = $this->getValueReal( $data );
275 return $values;
279 * Return options modified as an array ( name => value )
280 * @return array
282 public function getChangedValues() {
283 $values = array();
285 foreach ( $this->options as $name => $data ) {
286 if ( $data['value'] !== null ) {
287 $values[$name] = $data['value'];
291 return $values;
295 * Format options to an array ( name => value )
296 * @return array
298 public function getAllValues() {
299 $values = array();
301 foreach ( $this->options as $name => $data ) {
302 $values[$name] = $this->getValueReal( $data );
305 return $values;
308 # Reading values
311 * Fetch values for all options (or selected options) from the given WebRequest, making them
312 * available for accessing with getValue() or consumeValue() etc.
314 * @param WebRequest $r The request to fetch values from
315 * @param array $optionKeys Which options to fetch the values for (default:
316 * all of them). Note that passing an empty array will also result in
317 * values for all keys being fetched.
318 * @throws MWException If the type of any option is invalid
320 public function fetchValuesFromRequest( WebRequest $r, $optionKeys = null ) {
321 if ( !$optionKeys ) {
322 $optionKeys = array_keys( $this->options );
325 foreach ( $optionKeys as $name ) {
326 $default = $this->options[$name]['default'];
327 $type = $this->options[$name]['type'];
329 switch ( $type ) {
330 case self::BOOL:
331 $value = $r->getBool( $name, $default );
332 break;
333 case self::INT:
334 $value = $r->getInt( $name, $default );
335 break;
336 case self::STRING:
337 $value = $r->getText( $name, $default );
338 break;
339 case self::INTNULL:
340 $value = $r->getIntOrNull( $name );
341 break;
342 default:
343 throw new MWException( 'Unsupported datatype' );
346 if ( $value !== null ) {
347 $this->options[$name]['value'] = $value === $default ? null : $value;
352 /** @name ArrayAccess functions
353 * These functions implement the ArrayAccess PHP interface.
354 * @see http://php.net/manual/en/class.arrayaccess.php
356 /* @{ */
357 /** Whether the option exists. */
358 public function offsetExists( $name ) {
359 return isset( $this->options[$name] );
362 /** Retrieve an option value. */
363 public function offsetGet( $name ) {
364 return $this->getValue( $name );
367 /** Set an option to given value. */
368 public function offsetSet( $name, $value ) {
369 $this->setValue( $name, $value );
372 /** Delete the option. */
373 public function offsetUnset( $name ) {
374 $this->delete( $name );
376 /* @} */