You are here

function keycloak_form_openid_connect_admin_settings_submit in Keycloak OpenID Connect 8

Custom submit handler to alter submitted values of the settings form.

Parameters

array $form: An associative array containing the structure of the plugin form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

1 string reference to 'keycloak_form_openid_connect_admin_settings_submit'
keycloak_form_openid_connect_admin_settings_alter in ./keycloak.module
Implements hook_form_FORM_ID_alter() for openid_connect_admin_settings.

File

./keycloak.module, line 118
Hook implementations of the Keycloak module.

Code

function keycloak_form_openid_connect_admin_settings_submit(array &$form, FormStateInterface $form_state) {

  // Whether Keycloak is enabled and we have to sanitize
  // Keycloak setting values.
  if (empty($form_state
    ->getValue([
    'clients_enabled',
    'keycloak',
  ]))) {

    // Don't bother with sanitizing, as the Keycloak settings won't be saved.
    return;
  }

  // Sanitize Keycloak setting values.
  $settings = $form_state
    ->getValue([
    'clients',
    'keycloak',
    'settings',
  ]);

  // Remove trailing slashes from base URL.
  $settings['keycloak_base'] = rtrim($settings['keycloak_base'], '/ ');

  // Keycloak language mapping.
  $settings['keycloak_i18n']['enabled'] = !empty($settings['keycloak_i18n_enabled']);
  unset($settings['keycloak_i18n_enabled']);

  // Store those mappings only, that differ from default locales.
  $mappings = $settings['keycloak_i18n']['mapping'];
  $mappings_save = [];
  if (!empty($mappings)) {
    foreach ($mappings as $mapping) {
      if (empty($mapping['target']) || $mapping['langcode'] == $mapping['target']) {
        continue;
      }
      $mappings_save[] = $mapping;
    }
  }
  $settings['keycloak_i18n']['mapping'] = $mappings_save;

  // Keycloak groups mapping.
  $settings['keycloak_groups']['enabled'] = !empty($settings['keycloak_groups_enabled']);
  unset($settings['keycloak_groups_enabled']);
  $ruleset = $settings['keycloak_groups']['rules'];
  $rules = [];
  foreach ($ruleset as $rule) {
    if ($rule['role'] == 'NONE' || $rule['operation'] != 'empty' && $rule['operation'] != 'not_empty' && empty(trim($rule['pattern']))) {
      continue;
    }
    if ($rule['operation'] == 'empty' || $rule['operation'] == 'not_empty') {
      $rule['pattern'] = '';
      $rule['case_sensitive'] = FALSE;
    }
    unset($rule['delete']);
    $rules[] = $rule;
  }
  unset($settings['keycloak_groups']['add']);
  $settings['keycloak_groups']['rules'] = $rules;

  // Single sign-out.
  $settings['check_session']['enabled'] = !empty($settings['check_session_enabled']);
  unset($settings['check_session_enabled']);
  $form_state
    ->setValue([
    'clients',
    'keycloak',
    'settings',
  ], $settings);
}