Upgraded drupal core with security updates
[yaffs-website] / web / core / modules / language / src / Form / NegotiationBrowserForm.php
1 <?php
2
3 namespace Drupal\language\Form;
4
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 use Symfony\Component\DependencyInjection\ContainerInterface;
11
12 /**
13  * Configure the browser language negotiation method for this site.
14  */
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    * {@inheritdoc}
26    *
27    * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
28    *   The module handler
29    */
30   public function __construct(ConfigFactoryInterface $config_factory, ConfigurableLanguageManagerInterface $language_manager ) {
31     parent::__construct($config_factory);
32     $this->languageManager = $language_manager;
33   }
34
35   /**
36    * {@inheritdoc}
37    */
38   public static function create(ContainerInterface $container) {
39     return new static(
40       $container->get('config.factory'),
41       $container->get('language_manager')
42     );
43   }
44
45   /**
46    * {@inheritdoc}
47    */
48   public function getFormId() {
49     return 'language_negotiation_configure_browser_form';
50   }
51
52   /**
53    * {@inheritdoc}
54    */
55   protected function getEditableConfigNames() {
56     return ['language.mappings'];
57   }
58
59   /**
60    * {@inheritdoc}
61    */
62   public function buildForm(array $form, FormStateInterface $form_state) {
63     $form = [];
64
65     // Initialize a language list to the ones available, including English.
66     $languages = $this->languageManager->getLanguages();
67
68     $existing_languages = [];
69     foreach ($languages as $langcode => $language) {
70       $existing_languages[$langcode] = $language->getName();
71     }
72
73     // If we have no languages available, present the list of predefined languages
74     // only. If we do have already added languages, set up two option groups with
75     // the list of existing and then predefined languages.
76     if (empty($existing_languages)) {
77       $language_options = $this->languageManager->getStandardLanguageListWithoutConfigured();
78     }
79     else {
80       $language_options = [
81         (string) $this->t('Existing languages') => $existing_languages,
82         (string) $this->t('Languages not yet added') => $this->languageManager->getStandardLanguageListWithoutConfigured(),
83       ];
84     }
85
86     $form['mappings'] = [
87       '#type' => 'table',
88       '#header' => [
89         $this->t('Browser language code'),
90         $this->t('Site language'),
91         $this->t('Operations'),
92       ],
93       '#attributes' => ['id' => 'language-negotiation-browser'],
94       '#empty' => $this->t('No browser language mappings available.'),
95     ];
96
97     $mappings = $this->language_get_browser_drupal_langcode_mappings();
98     foreach ($mappings as $browser_langcode => $drupal_langcode) {
99       $form['mappings'][$browser_langcode] = [
100         'browser_langcode' => [
101           '#title' => $this->t('Browser language code'),
102           '#title_display' => 'invisible',
103           '#type' => 'textfield',
104           '#default_value' => $browser_langcode,
105           '#size' => 20,
106           '#required' => TRUE,
107         ],
108         'drupal_langcode' => [
109           '#title' => $this->t('Site language'),
110           '#title_display' => 'invisible',
111           '#type' => 'select',
112           '#options' => $language_options,
113           '#default_value' => $drupal_langcode,
114           '#required' => TRUE,
115         ],
116       ];
117       // Operations column.
118       $form['mappings'][$browser_langcode]['operations'] = [
119         '#type' => 'operations',
120         '#links' => [],
121       ];
122       $form['mappings'][$browser_langcode]['operations']['#links']['delete'] = [
123         'title' => $this->t('Delete'),
124         'url' => Url::fromRoute('language.negotiation_browser_delete', ['browser_langcode' => $browser_langcode]),
125       ];
126     }
127
128     // Add empty row.
129     $form['new_mapping'] = [
130       '#type' => 'details',
131       '#title' => $this->t('Add a new mapping'),
132       '#tree' => TRUE,
133     ];
134     $form['new_mapping']['browser_langcode'] = [
135       '#type' => 'textfield',
136       '#title' => $this->t('Browser language code'),
137       '#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/']),
138       '#size' => 20,
139     ];
140     $form['new_mapping']['drupal_langcode'] = [
141       '#type' => 'select',
142       '#title' => $this->t('Site language'),
143       '#options' => $language_options,
144     ];
145
146     return parent::buildForm($form, $form_state);
147   }
148
149   /**
150    * {@inheritdoc}
151    */
152   public function validateForm(array &$form, FormStateInterface $form_state) {
153     // Array to check if all browser language codes are unique.
154     $unique_values = [];
155
156     // Check all mappings.
157     if ($form_state->hasValue('mappings')) {
158       $mappings = $form_state->getValue('mappings');
159       foreach ($mappings as $key => $data) {
160         // Make sure browser_langcode is unique.
161         if (array_key_exists($data['browser_langcode'], $unique_values)) {
162           $form_state->setErrorByName('mappings][new_mapping][browser_langcode', $this->t('Browser language codes must be unique.'));
163         }
164         elseif (preg_match('/[^a-z\-]/', $data['browser_langcode'])) {
165           $form_state->setErrorByName('mappings][new_mapping][browser_langcode', $this->t('Browser language codes can only contain lowercase letters and a hyphen(-).'));
166         }
167         $unique_values[$data['browser_langcode']] = $data['drupal_langcode'];
168       }
169     }
170
171     // Check new mapping.
172     $data = $form_state->getValue('new_mapping');
173     if (!empty($data['browser_langcode'])) {
174       // Make sure browser_langcode is unique.
175       if (array_key_exists($data['browser_langcode'], $unique_values)) {
176         $form_state->setErrorByName('mappings][' . $key . '][browser_langcode', $this->t('Browser language codes must be unique.'));
177       }
178       elseif (preg_match('/[^a-z\-]/', $data['browser_langcode'])) {
179         $form_state->setErrorByName('mappings][' . $key . '][browser_langcode', $this->t('Browser language codes can only contain lowercase letters and a hyphen(-).'));
180       }
181       $unique_values[$data['browser_langcode']] = $data['drupal_langcode'];
182     }
183
184     $form_state->set('mappings', $unique_values);
185   }
186
187   /**
188    * {@inheritdoc}
189    */
190   public function submitForm(array &$form, FormStateInterface $form_state) {
191     $mappings = $form_state->get('mappings');
192     if (!empty($mappings)) {
193       $config = $this->config('language.mappings');
194       $config->setData(['map' => $mappings]);
195       $config->save();
196     }
197
198     parent::submitForm($form, $form_state);
199   }
200
201   /**
202    * Retrieves the browser's langcode mapping configuration array.
203    *
204    * @return array
205    *   The browser's langcode mapping configuration array.
206    */
207   protected function language_get_browser_drupal_langcode_mappings() {
208     $config = $this->config('language.mappings');
209     if ($config->isNew()) {
210       return [];
211     }
212     return $config->get('map');
213   }
214
215 }