You are here

admin_user_language.module in Admin User Language 8

File

admin_user_language.module
View source
<?php

/**
 * @file
 * Contains admin_user_language.module.
 */
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\user\Entity\User;

/**
 * Implements hook_help().
 *
 * @param string $route_name
 * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
 *
 * @return null|string
 */
function admin_user_language_help($route_name, RouteMatchInterface $route_match) {
  if ('help.page.admin_user_language' === $route_name) {

    // Main module help for the admin_user_language module.
    $output = '';
    $output .= '<h3>' . t('About') . '</h3>';
    $output .= '<p>' . t('Forces a preferred administration pages language on user creation/update') . '</p>';
    return $output;
  }
  return NULL;
}

/**
 * Implements hook_entity_presave().
 *
 * On user creation/edit makes sure that a preferred
 * admin language is selected.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 */
function admin_user_language_entity_presave(EntityInterface $entity) {
  if ($entity instanceof User) {

    /** @var Drupal\Core\Config\ConfigFactory $config */
    $config = \Drupal::service('config.factory')
      ->get('admin_user_language.settings');
    $default_language = $config
      ->get('default_language_to_assign');
    $languages = (array) \Drupal::service('language_manager')
      ->getLanguages();

    // Building an array of language code => language name.
    $active_languages = [];

    /** @var \Drupal\Core\Language\Language $lang */
    foreach ($languages as $lang) {
      $active_languages[$lang
        ->getId()] = $lang
        ->getName();
    }
    $prevent_user_override = $config
      ->get('prevent_user_override');
    if ($default_language && array_key_exists($default_language, $active_languages)) {
      if (TRUE === $prevent_user_override || $entity
        ->isNew()) {
        $entity
          ->set('preferred_admin_langcode', $default_language);
      }
    }
  }
}