Version 1
[yaffs-website] / web / core / lib / Drupal / Core / Form / OptGroup.php
1 <?php
2
3 namespace Drupal\Core\Form;
4
5 /**
6  * Provides helpers for HTML option groups.
7  */
8 class OptGroup {
9
10   /**
11    * Allows PHP array processing of multiple select options with the same value.
12    *
13    * Used for form select elements which need to validate HTML option groups
14    * and multiple options which may return the same value. Associative PHP
15    * arrays cannot handle these structures, since they share a common key.
16    *
17    * @param array $array
18    *   The form options array to process.
19    *
20    * @return array
21    *   An array with all hierarchical elements flattened to a single array.
22    */
23   public static function flattenOptions(array $array) {
24     $options = [];
25     static::doFlattenOptions($array, $options);
26     return $options;
27   }
28
29   /**
30    * Iterates over an array building a flat array with duplicate keys removed.
31    *
32    * This function also handles cases where objects are passed as array values.
33    *
34    * @param array $array
35    *   The form options array to process.
36    * @param array $options
37    *   The array of flattened options.
38    */
39   protected static function doFlattenOptions(array $array, array &$options) {
40     foreach ($array as $key => $value) {
41       if (is_object($value) && isset($value->option)) {
42         static::doFlattenOptions($value->option, $options);
43       }
44       elseif (is_array($value)) {
45         static::doFlattenOptions($value, $options);
46       }
47       else {
48         $options[$key] = $value;
49       }
50     }
51   }
52
53 }