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