51d91f91e3d7e1deaba080c7a682b2f50a6e82e4
[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 *
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.
12 *
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.
17 *
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
22 *
23 * @file
24 * @author Niklas Laxström
25 * @author Antoine Musso
26 */
27
28 /**
29 * Helper class to keep track of options when mixing links and form elements.
30 *
31 * @todo This badly needs some examples and tests :) The usage in SpecialRecentchanges class is a
32 * good ersatz in the meantime.
33 */
34 class FormOptions implements ArrayAccess {
35 /** @name Type constants
36 * Used internally to map an option value to a WebRequest accessor
37 */
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.
49 */
50 const INTNULL = 3;
51 /* @} */
52
53 /**
54 * Map of known option names to information about them.
55 *
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)
62 */
63 protected $options = array();
64
65 # Setting up
66
67 /**
68 * Add an option to be handled by this FormOptions instance.
69 *
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)
73 */
74 public function add( $name, $default, $type = self::AUTO ) {
75 $option = array();
76 $option['default'] = $default;
77 $option['value'] = null;
78 $option['consumed'] = false;
79
80 if ( $type !== self::AUTO ) {
81 $option['type'] = $type;
82 } else {
83 $option['type'] = self::guessType( $default );
84 }
85
86 $this->options[$name] = $option;
87 }
88
89 /**
90 * Remove an option being handled by this FormOptions instance. This is the inverse of add().
91 *
92 * @param string $name Request parameter name
93 */
94 public function delete( $name ) {
95 $this->validateName( $name, true );
96 unset( $this->options[$name] );
97 }
98
99 /**
100 * Used to find out which type the data is. All types are defined in the 'Type constants' section
101 * of this class.
102 *
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.
105 *
106 * @param mixed $data Value to guess the type for
107 * @throws MWException If unable to guess the type
108 * @return int Type constant
109 */
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' );
119 }
120 }
121
122 # Handling values
123
124 /**
125 * Verify that the given option name exists.
126 *
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
131 */
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;
138 }
139 }
140 return true;
141 }
142
143 /**
144 * Use to set the value of an option.
145 *
146 * @param string $name option name
147 * @param mixed $value value for the option
148 * @param bool $force Whether to set the value when it is equivalent to
149 * the default value for this option (default false).
150 */
151 public function setValue( $name, $value, $force = false ) {
152 $this->validateName( $name, true );
153
154 if ( !$force && $value === $this->options[$name]['default'] ) {
155 // null default values as unchanged
156 $this->options[$name]['value'] = null;
157 } else {
158 $this->options[$name]['value'] = $value;
159 }
160 }
161
162 /**
163 * Get the value for the given option name.
164 * Internally use getValueReal()
165 *
166 * @param string $name option name
167 * @return mixed
168 */
169 public function getValue( $name ) {
170 $this->validateName( $name, true );
171
172 return $this->getValueReal( $this->options[$name] );
173 }
174
175 /**
176 * @todo Document
177 * @param array $option array structure describing the option
178 * @return mixed Value or the default value if it is null
179 */
180 protected function getValueReal( $option ) {
181 if ( $option['value'] !== null ) {
182 return $option['value'];
183 } else {
184 return $option['default'];
185 }
186 }
187
188 /**
189 * Delete the option value.
190 * This will make future calls to getValue() return the default value.
191 * @param string $name Option name
192 */
193 public function reset( $name ) {
194 $this->validateName( $name, true );
195 $this->options[$name]['value'] = null;
196 }
197
198 /**
199 * Get the value of given option and mark it as 'consumed'. Consumed options are not returned
200 * by getUnconsumedValues().
201 *
202 * @see consumeValues()
203 * @throws MWException If the option does not exist
204 * @param string $name Option name
205 * @return mixed Value, or the default value if it is null
206 */
207 public function consumeValue( $name ) {
208 $this->validateName( $name, true );
209 $this->options[$name]['consumed'] = true;
210
211 return $this->getValueReal( $this->options[$name] );
212 }
213
214 /**
215 * Get the values of given options and mark them as 'consumed'. Consumed options are not returned
216 * by getUnconsumedValues().
217 *
218 * @see consumeValue()
219 * @throws MWException If any option does not exist
220 * @param array $names Array of option names as strings
221 * @return array Array of option values, or the default values if they are null
222 */
223 public function consumeValues( $names ) {
224 $out = array();
225
226 foreach ( $names as $name ) {
227 $this->validateName( $name, true );
228 $this->options[$name]['consumed'] = true;
229 $out[] = $this->getValueReal( $this->options[$name] );
230 }
231
232 return $out;
233 }
234
235 /**
236 * Validate and set an option integer value
237 * The value will be altered to fit in the range.
238 *
239 * @param string $name option name
240 * @param int $min minimum value
241 * @param int $max maximum value
242 * @throws MWException If option is not of type INT
243 */
244 public function validateIntBounds( $name, $min, $max ) {
245 $this->validateName( $name, true );
246
247 if ( $this->options[$name]['type'] !== self::INT ) {
248 throw new MWException( "Option $name is not of type int" );
249 }
250
251 $value = $this->getValueReal( $this->options[$name] );
252 $value = max( $min, min( $max, $value ) );
253
254 $this->setValue( $name, $value );
255 }
256
257 /**
258 * Get all remaining values which have not been consumed by consumeValue() or consumeValues().
259 *
260 * @param bool $all Whether to include unchanged options (default: false)
261 * @return array
262 */
263 public function getUnconsumedValues( $all = false ) {
264 $values = array();
265
266 foreach ( $this->options as $name => $data ) {
267 if ( !$data['consumed'] ) {
268 if ( $all || $data['value'] !== null ) {
269 $values[$name] = $this->getValueReal( $data );
270 }
271 }
272 }
273
274 return $values;
275 }
276
277 /**
278 * Return options modified as an array ( name => value )
279 * @return array
280 */
281 public function getChangedValues() {
282 $values = array();
283
284 foreach ( $this->options as $name => $data ) {
285 if ( $data['value'] !== null ) {
286 $values[$name] = $data['value'];
287 }
288 }
289
290 return $values;
291 }
292
293 /**
294 * Format options to an array ( name => value )
295 * @return array
296 */
297 public function getAllValues() {
298 $values = array();
299
300 foreach ( $this->options as $name => $data ) {
301 $values[$name] = $this->getValueReal( $data );
302 }
303
304 return $values;
305 }
306
307 # Reading values
308
309 /**
310 * Fetch values for all options (or selected options) from the given WebRequest, making them
311 * available for accessing with getValue() or consumeValue() etc.
312 *
313 * @param WebRequest $r The request to fetch values from
314 * @param array $optionKeys Which options to fetch the values for (default:
315 * all of them). Note that passing an empty array will also result in
316 * values for all keys being fetched.
317 * @throws MWException If the type of any option is invalid
318 */
319 public function fetchValuesFromRequest( WebRequest $r, $optionKeys = null ) {
320 if ( !$optionKeys ) {
321 $optionKeys = array_keys( $this->options );
322 }
323
324 foreach ( $optionKeys as $name ) {
325 $default = $this->options[$name]['default'];
326 $type = $this->options[$name]['type'];
327
328 switch ( $type ) {
329 case self::BOOL:
330 $value = $r->getBool( $name, $default );
331 break;
332 case self::INT:
333 $value = $r->getInt( $name, $default );
334 break;
335 case self::STRING:
336 $value = $r->getText( $name, $default );
337 break;
338 case self::INTNULL:
339 $value = $r->getIntOrNull( $name );
340 break;
341 default:
342 throw new MWException( 'Unsupported datatype' );
343 }
344
345 if ( $value !== null ) {
346 $this->options[$name]['value'] = $value === $default ? null : $value;
347 }
348 }
349 }
350
351 /** @name ArrayAccess functions
352 * These functions implement the ArrayAccess PHP interface.
353 * @see http://php.net/manual/en/class.arrayaccess.php
354 */
355 /* @{ */
356 /** Whether the option exists. */
357 public function offsetExists( $name ) {
358 return isset( $this->options[$name] );
359 }
360
361 /** Retrieve an option value. */
362 public function offsetGet( $name ) {
363 return $this->getValue( $name );
364 }
365
366 /** Set an option to given value. */
367 public function offsetSet( $name, $value ) {
368 $this->setValue( $name, $value );
369 }
370
371 /** Delete the option. */
372 public function offsetUnset( $name ) {
373 $this->delete( $name );
374 }
375 /* @} */
376 }