OptGroup.php 1.4 KB

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