NegotiationBrowserForm.php 6.93 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\language\Form;

5
use Drupal\Core\Config\ConfigFactoryInterface;
6
use Drupal\Core\Form\ConfigFormBase;
7
use Drupal\Core\Form\FormStateInterface;
8
use Drupal\Core\Url;
9
use Drupal\language\ConfigurableLanguageManagerInterface;
10 11 12 13 14
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Configure the browser language negotiation method for this site.
 */
15
class NegotiationBrowserForm extends ConfigFormBase {
16 17

  /**
18
   * The configurable language manager.
19
   *
20
   * @var \Drupal\language\ConfigurableLanguageManagerInterface
21
   */
22
  protected $languageManager;
23 24 25 26

  /**
   * {@inheritdoc}
   */
27
  public function __construct(ConfigFactoryInterface $config_factory, ConfigurableLanguageManagerInterface $language_manager ) {
28
    parent::__construct($config_factory);
29
    $this->languageManager = $language_manager;
30 31 32 33 34 35 36 37
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('config.factory'),
38
      $container->get('language_manager')
39 40 41 42 43 44
    );
  }

  /**
   * {@inheritdoc}
   */
45
  public function getFormId() {
46 47 48
    return 'language_negotiation_configure_browser_form';
  }

49 50 51 52 53 54 55
  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return ['language.mappings'];
  }

56 57 58
  /**
   * {@inheritdoc}
   */
59
  public function buildForm(array $form, FormStateInterface $form_state) {
60
    $form = [];
61 62

    // Initialize a language list to the ones available, including English.
63
    $languages = $this->languageManager->getLanguages();
64

65
    $existing_languages = [];
66
    foreach ($languages as $langcode => $language) {
67
      $existing_languages[$langcode] = $language->getName();
68 69 70 71 72 73
    }

    // If we have no languages available, present the list of predefined languages
    // only. If we do have already added languages, set up two option groups with
    // the list of existing and then predefined languages.
    if (empty($existing_languages)) {
74
      $language_options = $this->languageManager->getStandardLanguageListWithoutConfigured();
75 76
    }
    else {
77
      $language_options = [
78 79
        (string) $this->t('Existing languages') => $existing_languages,
        (string) $this->t('Languages not yet added') => $this->languageManager->getStandardLanguageListWithoutConfigured(),
80
      ];
81 82
    }

83 84 85 86 87 88 89 90 91 92
    $form['mappings'] = [
      '#type' => 'table',
      '#header' => [
        $this->t('Browser language code'),
        $this->t('Site language'),
        $this->t('Operations'),
      ],
      '#attributes' => ['id' => 'language-negotiation-browser'],
      '#empty' => $this->t('No browser language mappings available.'),
    ];
93 94 95

    $mappings = $this->language_get_browser_drupal_langcode_mappings();
    foreach ($mappings as $browser_langcode => $drupal_langcode) {
96 97
      $form['mappings'][$browser_langcode] = [
        'browser_langcode' => [
98 99
          '#title' => $this->t('Browser language code'),
          '#title_display' => 'invisible',
100 101 102 103
          '#type' => 'textfield',
          '#default_value' => $browser_langcode,
          '#size' => 20,
          '#required' => TRUE,
104 105
        ],
        'drupal_langcode' => [
106 107
          '#title' => $this->t('Site language'),
          '#title_display' => 'invisible',
108 109 110 111
          '#type' => 'select',
          '#options' => $language_options,
          '#default_value' => $drupal_langcode,
          '#required' => TRUE,
112 113
        ],
      ];
114 115 116 117 118 119 120 121 122
      // Operations column.
      $form['mappings'][$browser_langcode]['operations'] = [
        '#type' => 'operations',
        '#links' => [],
      ];
      $form['mappings'][$browser_langcode]['operations']['#links']['delete'] = [
        'title' => $this->t('Delete'),
        'url' => Url::fromRoute('language.negotiation_browser_delete', ['browser_langcode' => $browser_langcode]),
      ];
123 124 125
    }

    // Add empty row.
126
    $form['new_mapping'] = [
127 128 129
      '#type' => 'details',
      '#title' => $this->t('Add a new mapping'),
      '#tree' => TRUE,
130 131
    ];
    $form['new_mapping']['browser_langcode'] = [
132 133
      '#type' => 'textfield',
      '#title' => $this->t('Browser language code'),
134
      '#description' => $this->t('Use language codes as <a href=":w3ctags">defined by the W3C</a> for interoperability. <em>Examples: "en", "en-gb" and "zh-hant".</em>', [':w3ctags' => 'http://www.w3.org/International/articles/language-tags/']),
135
      '#size' => 20,
136 137
    ];
    $form['new_mapping']['drupal_langcode'] = [
138
      '#type' => 'select',
139
      '#title' => $this->t('Site language'),
140
      '#options' => $language_options,
141
    ];
142 143 144 145 146 147 148

    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
149
  public function validateForm(array &$form, FormStateInterface $form_state) {
150
    // Array to check if all browser language codes are unique.
151
    $unique_values = [];
152 153

    // Check all mappings.
154 155
    if ($form_state->hasValue('mappings')) {
      $mappings = $form_state->getValue('mappings');
156 157 158
      foreach ($mappings as $key => $data) {
        // Make sure browser_langcode is unique.
        if (array_key_exists($data['browser_langcode'], $unique_values)) {
159
          $form_state->setErrorByName('mappings][new_mapping][browser_langcode', $this->t('Browser language codes must be unique.'));
160 161
        }
        elseif (preg_match('/[^a-z\-]/', $data['browser_langcode'])) {
162
          $form_state->setErrorByName('mappings][new_mapping][browser_langcode', $this->t('Browser language codes can only contain lowercase letters and a hyphen(-).'));
163 164 165 166 167 168
        }
        $unique_values[$data['browser_langcode']] = $data['drupal_langcode'];
      }
    }

    // Check new mapping.
169
    $data = $form_state->getValue('new_mapping');
170 171 172
    if (!empty($data['browser_langcode'])) {
      // Make sure browser_langcode is unique.
      if (array_key_exists($data['browser_langcode'], $unique_values)) {
173
        $form_state->setErrorByName('mappings][' . $key . '][browser_langcode', $this->t('Browser language codes must be unique.'));
174 175
      }
      elseif (preg_match('/[^a-z\-]/', $data['browser_langcode'])) {
176
        $form_state->setErrorByName('mappings][' . $key . '][browser_langcode', $this->t('Browser language codes can only contain lowercase letters and a hyphen(-).'));
177 178 179 180
      }
      $unique_values[$data['browser_langcode']] = $data['drupal_langcode'];
    }

181
    $form_state->set('mappings', $unique_values);
182 183 184 185 186
  }

  /**
   * {@inheritdoc}
   */
187
  public function submitForm(array &$form, FormStateInterface $form_state) {
188
    $mappings = $form_state->get('mappings');
189
    if (!empty($mappings)) {
190
      $config = $this->config('language.mappings');
191
      $config->setData(['map' => $mappings]);
192 193 194 195 196 197 198 199 200 201 202 203 204
      $config->save();
    }

    parent::submitForm($form, $form_state);
  }

  /**
   * Retrieves the browser's langcode mapping configuration array.
   *
   * @return array
   *   The browser's langcode mapping configuration array.
   */
  protected function language_get_browser_drupal_langcode_mappings() {
205
    $config = $this->config('language.mappings');
206
    if ($config->isNew()) {
207
      return [];
208
    }
209
    return $config->get('map');
210
  }
211

212
}