NegotiationBrowserForm.php 6.95 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
use Symfony\Component\DependencyInjection\ContainerInterface;

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

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

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

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

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

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

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

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

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

    // 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)) {
76
      $language_options = $this->languageManager->getStandardLanguageListWithoutConfigured();
77 78
    }
    else {
79
      $language_options = [
80 81
        (string) $this->t('Existing languages') => $existing_languages,
        (string) $this->t('Languages not yet added') => $this->languageManager->getStandardLanguageListWithoutConfigured(),
82
      ];
83 84
    }

85 86 87 88 89 90 91 92 93 94
    $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.'),
    ];
95 96 97

    $mappings = $this->language_get_browser_drupal_langcode_mappings();
    foreach ($mappings as $browser_langcode => $drupal_langcode) {
98 99
      $form['mappings'][$browser_langcode] = [
        'browser_langcode' => [
100 101
          '#title' => $this->t('Browser language code'),
          '#title_display' => 'invisible',
102 103 104 105
          '#type' => 'textfield',
          '#default_value' => $browser_langcode,
          '#size' => 20,
          '#required' => TRUE,
106 107
        ],
        'drupal_langcode' => [
108 109
          '#title' => $this->t('Site language'),
          '#title_display' => 'invisible',
110 111 112 113
          '#type' => 'select',
          '#options' => $language_options,
          '#default_value' => $drupal_langcode,
          '#required' => TRUE,
114 115
        ],
      ];
116 117 118 119 120 121 122 123 124
      // 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]),
      ];
125 126 127
    }

    // Add empty row.
128
    $form['new_mapping'] = [
129 130 131
      '#type' => 'details',
      '#title' => $this->t('Add a new mapping'),
      '#tree' => TRUE,
132 133
    ];
    $form['new_mapping']['browser_langcode'] = [
134 135
      '#type' => 'textfield',
      '#title' => $this->t('Browser language code'),
136
      '#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/']),
137
      '#size' => 20,
138 139
    ];
    $form['new_mapping']['drupal_langcode'] = [
140
      '#type' => 'select',
141
      '#title' => $this->t('Site language'),
142
      '#options' => $language_options,
143
    ];
144 145 146 147 148 149 150

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

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

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

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

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

  /**
   * {@inheritdoc}
   */
189
  public function submitForm(array &$form, FormStateInterface $form_state) {
190
    $mappings = $form_state->get('mappings');
191
    if (!empty($mappings)) {
192
      $config = $this->config('language.mappings');
193
      $config->setData(['map' => $mappings]);
194 195 196 197 198 199 200 201 202 203 204 205 206
      $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() {
207
    $config = $this->config('language.mappings');
208
    if ($config->isNew()) {
209
      return [];
210
    }
211
    return $config->get('map');
212
  }
213

214
}