<?php

/**
 * @file
 * Contains hooks for the config entity reference selection module.
 */

use Drupal\Core\Form\OptGroup;

/**
 * Implements hook_options_list_alter().
 */
function config_entity_reference_selection_options_list_alter(array &$options, array $context) {
  if (isset($context['fieldDefinition']) && $field_definition = $context['fieldDefinition']) {
    /** @var \Drupal\Core\Field\FieldDefinitionInterface $field_definition */

    $settings = $field_definition->getSettings();

    // Webforms are a corner-case that define their options via optgroups.
    if (!empty($settings['handler']) && $settings['handler'] === 'config:webform') {
      $handler_settings = $field_definition->getSetting('handler_settings');

      if ($allowed = $handler_settings['filter']['allowed_ids']) {
        $options = OptGroup::flattenOptions($options);
        $options = array_filter($options, static function ($k) use ($allowed) {
          return in_array($k, $allowed, TRUE);
        }, ARRAY_FILTER_USE_KEY);
      }

    }
  }
}
