summaryrefslogtreecommitdiff
path: root/includes/FormOptions.php
blob: c91c336762f645330fa0180d9b5297262982441e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
<?php
/**
 * Helper class to keep track of options when mixing links and form elements.
 *
 * Copyright © 2008, Niklas Laxström
 * Copyright © 2011, Antoine Musso
 * Copyright © 2013, Bartosz Dziewoński
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @author Niklas Laxström
 * @author Antoine Musso
 */

/**
 * Helper class to keep track of options when mixing links and form elements.
 *
 * @todo This badly needs some examples and tests :) The usage in SpecialRecentchanges class is a
 *     good ersatz in the meantime.
 */
class FormOptions implements ArrayAccess {
	/** @name Type constants
	 * Used internally to map an option value to a WebRequest accessor
	 */
	/* @{ */
	/** Mark value for automatic detection (for simple data types only) */
	const AUTO = -1;
	/** String type, maps guessType() to WebRequest::getText() */
	const STRING = 0;
	/** Integer type, maps guessType() to WebRequest::getInt() */
	const INT = 1;
	/** Float type, maps guessType() to WebRequest::getFloat()
	 * @since 1.23 */
	const FLOAT = 4;
	/** Boolean type, maps guessType() to WebRequest::getBool() */
	const BOOL = 2;
	/** Integer type or null, maps to WebRequest::getIntOrNull()
	 * This is useful for the namespace selector.
	 */
	const INTNULL = 3;
	/* @} */

	/**
	 * Map of known option names to information about them.
	 *
	 * Each value is an array with the following keys:
	 * - 'default' - the default value as passed to add()
	 * - 'value' - current value, start with null, can be set by various functions
	 * - 'consumed' - true/false, whether the option was consumed using
	 *   consumeValue() or consumeValues()
	 * - 'type' - one of the type constants (but never AUTO)
	 */
	protected $options = array();

	# Setting up

	/**
	 * Add an option to be handled by this FormOptions instance.
	 *
	 * @param string $name Request parameter name
	 * @param mixed $default Default value when the request parameter is not present
	 * @param int $type One of the type constants (optional, defaults to AUTO)
	 */
	public function add( $name, $default, $type = self::AUTO ) {
		$option = array();
		$option['default'] = $default;
		$option['value'] = null;
		$option['consumed'] = false;

		if ( $type !== self::AUTO ) {
			$option['type'] = $type;
		} else {
			$option['type'] = self::guessType( $default );
		}

		$this->options[$name] = $option;
	}

	/**
	 * Remove an option being handled by this FormOptions instance. This is the inverse of add().
	 *
	 * @param string $name Request parameter name
	 */
	public function delete( $name ) {
		$this->validateName( $name, true );
		unset( $this->options[$name] );
	}

	/**
	 * Used to find out which type the data is. All types are defined in the 'Type constants' section
	 * of this class.
	 *
	 * Detection of the INTNULL type is not supported; INT will be assumed if the data is an integer,
	 * MWException will be thrown if it's null.
	 *
	 * @param mixed $data Value to guess the type for
	 * @throws MWException If unable to guess the type
	 * @return int Type constant
	 */
	public static function guessType( $data ) {
		if ( is_bool( $data ) ) {
			return self::BOOL;
		} elseif ( is_int( $data ) ) {
			return self::INT;
		} elseif ( is_float( $data ) ) {
			return self::FLOAT;
		} elseif ( is_string( $data ) ) {
			return self::STRING;
		} else {
			throw new MWException( 'Unsupported datatype' );
		}
	}

	# Handling values

	/**
	 * Verify that the given option name exists.
	 *
	 * @param string $name Option name
	 * @param bool $strict Throw an exception when the option doesn't exist instead of returning false
	 * @throws MWException
	 * @return bool True if the option exists, false otherwise
	 */
	public function validateName( $name, $strict = false ) {
		if ( !isset( $this->options[$name] ) ) {
			if ( $strict ) {
				throw new MWException( "Invalid option $name" );
			} else {
				return false;
			}
		}

		return true;
	}

	/**
	 * Use to set the value of an option.
	 *
	 * @param string $name Option name
	 * @param mixed $value Value for the option
	 * @param bool $force Whether to set the value when it is equivalent to the default value for this
	 *     option (default false).
	 */
	public function setValue( $name, $value, $force = false ) {
		$this->validateName( $name, true );

		if ( !$force && $value === $this->options[$name]['default'] ) {
			// null default values as unchanged
			$this->options[$name]['value'] = null;
		} else {
			$this->options[$name]['value'] = $value;
		}
	}

	/**
	 * Get the value for the given option name. Uses getValueReal() internally.
	 *
	 * @param string $name Option name
	 * @return mixed
	 */
	public function getValue( $name ) {
		$this->validateName( $name, true );

		return $this->getValueReal( $this->options[$name] );
	}

	/**
	 * Return current option value, based on a structure taken from $options.
	 *
	 * @param array $option Array structure describing the option
	 * @return mixed Value, or the default value if it is null
	 */
	protected function getValueReal( $option ) {
		if ( $option['value'] !== null ) {
			return $option['value'];
		} else {
			return $option['default'];
		}
	}

	/**
	 * Delete the option value.
	 * This will make future calls to getValue() return the default value.
	 * @param string $name Option name
	 */
	public function reset( $name ) {
		$this->validateName( $name, true );
		$this->options[$name]['value'] = null;
	}

	/**
	 * Get the value of given option and mark it as 'consumed'. Consumed options are not returned
	 * by getUnconsumedValues().
	 *
	 * @see consumeValues()
	 * @throws MWException If the option does not exist
	 * @param string $name Option name
	 * @return mixed Value, or the default value if it is null
	 */
	public function consumeValue( $name ) {
		$this->validateName( $name, true );
		$this->options[$name]['consumed'] = true;

		return $this->getValueReal( $this->options[$name] );
	}

	/**
	 * Get the values of given options and mark them as 'consumed'. Consumed options are not returned
	 * by getUnconsumedValues().
	 *
	 * @see consumeValue()
	 * @throws MWException If any option does not exist
	 * @param array $names Array of option names as strings
	 * @return array Array of option values, or the default values if they are null
	 */
	public function consumeValues( $names ) {
		$out = array();

		foreach ( $names as $name ) {
			$this->validateName( $name, true );
			$this->options[$name]['consumed'] = true;
			$out[] = $this->getValueReal( $this->options[$name] );
		}

		return $out;
	}

	/**
	 * @see validateBounds()
	 */
	public function validateIntBounds( $name, $min, $max ) {
		$this->validateBounds( $name, $min, $max );
	}

	/**
	 * Constrain a numeric value for a given option to a given range. The value will be altered to fit
	 * in the range.
	 *
	 * @since 1.23
	 *
	 * @param string $name Option name
	 * @param int|float $min Minimum value
	 * @param int|float $max Maximum value
	 * @throws MWException If option is not of type INT
	 */
	public function validateBounds( $name, $min, $max ) {
		$this->validateName( $name, true );
		$type = $this->options[$name]['type'];

		if ( $type !== self::INT && $type !== self::FLOAT ) {
			throw new MWException( "Option $name is not of type INT or FLOAT" );
		}

		$value = $this->getValueReal( $this->options[$name] );
		$value = max( $min, min( $max, $value ) );

		$this->setValue( $name, $value );
	}

	/**
	 * Get all remaining values which have not been consumed by consumeValue() or consumeValues().
	 *
	 * @param bool $all Whether to include unchanged options (default: false)
	 * @return array
	 */
	public function getUnconsumedValues( $all = false ) {
		$values = array();

		foreach ( $this->options as $name => $data ) {
			if ( !$data['consumed'] ) {
				if ( $all || $data['value'] !== null ) {
					$values[$name] = $this->getValueReal( $data );
				}
			}
		}

		return $values;
	}

	/**
	 * Return options modified as an array ( name => value )
	 * @return array
	 */
	public function getChangedValues() {
		$values = array();

		foreach ( $this->options as $name => $data ) {
			if ( $data['value'] !== null ) {
				$values[$name] = $data['value'];
			}
		}

		return $values;
	}

	/**
	 * Format options to an array ( name => value )
	 * @return array
	 */
	public function getAllValues() {
		$values = array();

		foreach ( $this->options as $name => $data ) {
			$values[$name] = $this->getValueReal( $data );
		}

		return $values;
	}

	# Reading values

	/**
	 * Fetch values for all options (or selected options) from the given WebRequest, making them
	 * available for accessing with getValue() or consumeValue() etc.
	 *
	 * @param WebRequest $r The request to fetch values from
	 * @param array $optionKeys Which options to fetch the values for (default:
	 *     all of them). Note that passing an empty array will also result in
	 *     values for all keys being fetched.
	 * @throws MWException If the type of any option is invalid
	 */
	public function fetchValuesFromRequest( WebRequest $r, $optionKeys = null ) {
		if ( !$optionKeys ) {
			$optionKeys = array_keys( $this->options );
		}

		foreach ( $optionKeys as $name ) {
			$default = $this->options[$name]['default'];
			$type = $this->options[$name]['type'];

			switch ( $type ) {
				case self::BOOL:
					$value = $r->getBool( $name, $default );
					break;
				case self::INT:
					$value = $r->getInt( $name, $default );
					break;
				case self::FLOAT:
					$value = $r->getFloat( $name, $default );
					break;
				case self::STRING:
					$value = $r->getText( $name, $default );
					break;
				case self::INTNULL:
					$value = $r->getIntOrNull( $name );
					break;
				default:
					throw new MWException( 'Unsupported datatype' );
			}

			if ( $value !== null ) {
				$this->options[$name]['value'] = $value === $default ? null : $value;
			}
		}
	}

	/** @name ArrayAccess functions
	 * These functions implement the ArrayAccess PHP interface.
	 * @see http://php.net/manual/en/class.arrayaccess.php
	 */
	/* @{ */
	/**
	 * Whether the option exists.
	 * @param string $name
	 * @return bool
	 */
	public function offsetExists( $name ) {
		return isset( $this->options[$name] );
	}

	/**
	 * Retrieve an option value.
	 * @param string $name
	 * @return mixed
	 */
	public function offsetGet( $name ) {
		return $this->getValue( $name );
	}

	/**
	 * Set an option to given value.
	 * @param string $name
	 * @param mixed $value
	 */
	public function offsetSet( $name, $value ) {
		$this->setValue( $name, $value );
	}

	/**
	 * Delete the option.
	 * @param string $name
	 */
	public function offsetUnset( $name ) {
		$this->delete( $name );
	}
	/* @} */
}