Merge "Add "extended" file metadata to API"
[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
141 return true;
142 }
143
144 /**
145 * Use to set the value of an option.
146 *
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).
151 */
152 public function setValue( $name, $value, $force = false ) {
153 $this->validateName( $name, true );
154
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;
160 }
161 }
162
163 /**
164 * Get the value for the given option name. Uses getValueReal() internally.
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 * Return current option value, based on a structure taken from $options.
177 *
178 * @param array $option Array structure describing the option
179 * @return mixed Value, or the default value if it is null
180 */
181 protected function getValueReal( $option ) {
182 if ( $option['value'] !== null ) {
183 return $option['value'];
184 } else {
185 return $option['default'];
186 }
187 }
188
189 /**
190 * Delete the option value.
191 * This will make future calls to getValue() return the default value.
192 * @param string $name Option name
193 */
194 public function reset( $name ) {
195 $this->validateName( $name, true );
196 $this->options[$name]['value'] = null;
197 }
198
199 /**
200 * Get the value of given option and mark it as 'consumed'. Consumed options are not returned
201 * by getUnconsumedValues().
202 *
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
207 */
208 public function consumeValue( $name ) {
209 $this->validateName( $name, true );
210 $this->options[$name]['consumed'] = true;
211
212 return $this->getValueReal( $this->options[$name] );
213 }
214
215 /**
216 * Get the values of given options and mark them as 'consumed'. Consumed options are not returned
217 * by getUnconsumedValues().
218 *
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
223 */
224 public function consumeValues( $names ) {
225 $out = array();
226
227 foreach ( $names as $name ) {
228 $this->validateName( $name, true );
229 $this->options[$name]['consumed'] = true;
230 $out[] = $this->getValueReal( $this->options[$name] );
231 }
232
233 return $out;
234 }
235
236 /**
237 * Validate and set an option integer value
238 * The value will be altered to fit in the range.
239 *
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
244 */
245 public function validateIntBounds( $name, $min, $max ) {
246 $this->validateName( $name, true );
247
248 if ( $this->options[$name]['type'] !== self::INT ) {
249 throw new MWException( "Option $name is not of type int" );
250 }
251
252 $value = $this->getValueReal( $this->options[$name] );
253 $value = max( $min, min( $max, $value ) );
254
255 $this->setValue( $name, $value );
256 }
257
258 /**
259 * Get all remaining values which have not been consumed by consumeValue() or consumeValues().
260 *
261 * @param bool $all Whether to include unchanged options (default: false)
262 * @return array
263 */
264 public function getUnconsumedValues( $all = false ) {
265 $values = array();
266
267 foreach ( $this->options as $name => $data ) {
268 if ( !$data['consumed'] ) {
269 if ( $all || $data['value'] !== null ) {
270 $values[$name] = $this->getValueReal( $data );
271 }
272 }
273 }
274
275 return $values;
276 }
277
278 /**
279 * Return options modified as an array ( name => value )
280 * @return array
281 */
282 public function getChangedValues() {
283 $values = array();
284
285 foreach ( $this->options as $name => $data ) {
286 if ( $data['value'] !== null ) {
287 $values[$name] = $data['value'];
288 }
289 }
290
291 return $values;
292 }
293
294 /**
295 * Format options to an array ( name => value )
296 * @return array
297 */
298 public function getAllValues() {
299 $values = array();
300
301 foreach ( $this->options as $name => $data ) {
302 $values[$name] = $this->getValueReal( $data );
303 }
304
305 return $values;
306 }
307
308 # Reading values
309
310 /**
311 * Fetch values for all options (or selected options) from the given WebRequest, making them
312 * available for accessing with getValue() or consumeValue() etc.
313 *
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
319 */
320 public function fetchValuesFromRequest( WebRequest $r, $optionKeys = null ) {
321 if ( !$optionKeys ) {
322 $optionKeys = array_keys( $this->options );
323 }
324
325 foreach ( $optionKeys as $name ) {
326 $default = $this->options[$name]['default'];
327 $type = $this->options[$name]['type'];
328
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' );
344 }
345
346 if ( $value !== null ) {
347 $this->options[$name]['value'] = $value === $default ? null : $value;
348 }
349 }
350 }
351
352 /** @name ArrayAccess functions
353 * These functions implement the ArrayAccess PHP interface.
354 * @see http://php.net/manual/en/class.arrayaccess.php
355 */
356 /* @{ */
357 /** Whether the option exists. */
358 public function offsetExists( $name ) {
359 return isset( $this->options[$name] );
360 }
361
362 /** Retrieve an option value. */
363 public function offsetGet( $name ) {
364 return $this->getValue( $name );
365 }
366
367 /** Set an option to given value. */
368 public function offsetSet( $name, $value ) {
369 $this->setValue( $name, $value );
370 }
371
372 /** Delete the option. */
373 public function offsetUnset( $name ) {
374 $this->delete( $name );
375 }
376 /* @} */
377 }