325a4351b01d913392731ff14d630f5957709353
[yaffs-website] / web / core / modules / language / src / Form / NegotiationConfigureForm.php
1 <?php
2
3 namespace Drupal\language\Form;
4
5 use Drupal\Core\Block\BlockManagerInterface;
6 use Drupal\Component\Utility\Unicode;
7 use Drupal\Core\Config\ConfigFactoryInterface;
8 use Drupal\Core\Entity\EntityStorageInterface;
9 use Drupal\Core\Extension\ThemeHandlerInterface;
10 use Drupal\Core\Form\ConfigFormBase;
11 use Drupal\Core\Form\FormStateInterface;
12 use Drupal\Core\Url;
13 use Drupal\language\ConfigurableLanguageManagerInterface;
14 use Drupal\language\LanguageNegotiatorInterface;
15 use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationSelected;
16 use Symfony\Component\DependencyInjection\ContainerInterface;
17
18 /**
19  * Configure the selected language negotiation method for this site.
20  *
21  * @internal
22  */
23 class NegotiationConfigureForm extends ConfigFormBase {
24
25   /**
26    * Stores the configuration object for language.types.
27    *
28    * @var \Drupal\Core\Config\Config
29    */
30   protected $languageTypes;
31
32   /**
33    * The language manager.
34    *
35    * @var \Drupal\language\ConfigurableLanguageManagerInterface
36    */
37   protected $languageManager;
38
39   /**
40    * The language negotiator.
41    *
42    * @var \Drupal\language\LanguageNegotiatorInterface
43    */
44   protected $negotiator;
45
46   /**
47    * The block manager.
48    *
49    * @var \Drupal\Core\Block\BlockManagerInterface
50    */
51   protected $blockManager;
52
53   /**
54    * The block storage.
55    *
56    * @var \Drupal\Core\Entity\EntityStorageInterface|null
57    */
58   protected $blockStorage;
59
60   /**
61    * The theme handler.
62    *
63    * @var \Drupal\Core\Extension\ThemeHandlerInterface
64    */
65   protected $themeHandler;
66
67   /**
68    * Constructs a NegotiationConfigureForm object.
69    *
70    * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
71    *   The factory for configuration objects.
72    * @param \Drupal\language\ConfigurableLanguageManagerInterface $language_manager
73    *   The language manager.
74    * @param \Drupal\language\LanguageNegotiatorInterface $negotiator
75    *   The language negotiation methods manager.
76    * @param \Drupal\Core\Block\BlockManagerInterface $block_manager
77    *   The block manager.
78    * @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler
79    *   The theme handler.
80    * @param \Drupal\Core\Entity\EntityStorageInterface $block_storage
81    *   The block storage, or NULL if not available.
82    */
83   public function __construct(ConfigFactoryInterface $config_factory, ConfigurableLanguageManagerInterface $language_manager, LanguageNegotiatorInterface $negotiator, BlockManagerInterface $block_manager, ThemeHandlerInterface $theme_handler, EntityStorageInterface $block_storage = NULL) {
84     parent::__construct($config_factory);
85     $this->languageTypes = $this->config('language.types');
86     $this->languageManager = $language_manager;
87     $this->negotiator = $negotiator;
88     $this->blockManager = $block_manager;
89     $this->themeHandler = $theme_handler;
90     $this->blockStorage = $block_storage;
91   }
92
93   /**
94    * {@inheritdoc}
95    */
96   public static function create(ContainerInterface $container) {
97     $entity_manager = $container->get('entity.manager');
98     $block_storage = $entity_manager->hasHandler('block', 'storage') ? $entity_manager->getStorage('block') : NULL;
99     return new static(
100       $container->get('config.factory'),
101       $container->get('language_manager'),
102       $container->get('language_negotiator'),
103       $container->get('plugin.manager.block'),
104       $container->get('theme_handler'),
105       $block_storage
106     );
107   }
108
109   /**
110    * {@inheritdoc}
111    */
112   public function getFormId() {
113     return 'language_negotiation_configure_form';
114   }
115
116   /**
117    * {@inheritdoc}
118    */
119   protected function getEditableConfigNames() {
120     return ['language.types'];
121   }
122
123   /**
124    * {@inheritdoc}
125    */
126   public function buildForm(array $form, FormStateInterface $form_state) {
127     $configurable = $this->languageTypes->get('configurable');
128
129     $form = [
130       '#theme' => 'language_negotiation_configure_form',
131       '#language_types_info' => $this->languageManager->getDefinedLanguageTypesInfo(),
132       '#language_negotiation_info' => $this->negotiator->getNegotiationMethods(),
133     ];
134     $form['#language_types'] = [];
135
136     foreach ($form['#language_types_info'] as $type => $info) {
137       // Show locked language types only if they are configurable.
138       if (empty($info['locked']) || in_array($type, $configurable)) {
139         $form['#language_types'][] = $type;
140       }
141     }
142
143     foreach ($form['#language_types'] as $type) {
144       $this->configureFormTable($form, $type);
145     }
146
147     $form['actions'] = ['#type' => 'actions'];
148     $form['actions']['submit'] = [
149       '#type' => 'submit',
150       '#button_type' => 'primary',
151       '#value' => $this->t('Save settings'),
152     ];
153
154     return $form;
155   }
156
157   /**
158    * {@inheritdoc}
159    */
160   public function submitForm(array &$form, FormStateInterface $form_state) {
161     $configurable_types = $form['#language_types'];
162
163     $stored_values = $this->languageTypes->get('configurable');
164     $customized = [];
165     $method_weights_type = [];
166
167     foreach ($configurable_types as $type) {
168       $customized[$type] = in_array($type, $stored_values);
169       $method_weights = [];
170       $enabled_methods = $form_state->getValue([$type, 'enabled']);
171       $enabled_methods[LanguageNegotiationSelected::METHOD_ID] = TRUE;
172       $method_weights_input = $form_state->getValue([$type, 'weight']);
173       if ($form_state->hasValue([$type, 'configurable'])) {
174         $customized[$type] = !$form_state->isValueEmpty([$type, 'configurable']);
175       }
176
177       foreach ($method_weights_input as $method_id => $weight) {
178         if ($enabled_methods[$method_id]) {
179           $method_weights[$method_id] = $weight;
180         }
181       }
182
183       $method_weights_type[$type] = $method_weights;
184       $this->languageTypes->set('negotiation.' . $type . '.method_weights', $method_weights_input)->save();
185     }
186
187     // Update non-configurable language types and the related language
188     // negotiation configuration.
189     $this->negotiator->updateConfiguration(array_keys(array_filter($customized)));
190
191     // Update the language negotiations after setting the configurability.
192     foreach ($method_weights_type as $type => $method_weights) {
193       $this->negotiator->saveConfiguration($type, $method_weights);
194     }
195
196     // Clear block definitions cache since the available blocks and their names
197     // may have been changed based on the configurable types.
198     if ($this->blockStorage) {
199       // If there is an active language switcher for a language type that has
200       // been made not configurable, deactivate it first.
201       $non_configurable = array_keys(array_diff($customized, array_filter($customized)));
202       $this->disableLanguageSwitcher($non_configurable);
203     }
204     $this->blockManager->clearCachedDefinitions();
205
206     $form_state->setRedirect('language.negotiation');
207     drupal_set_message($this->t('Language detection configuration saved.'));
208   }
209
210   /**
211    * Builds a language negotiation method configuration table.
212    *
213    * @param array $form
214    *   The language negotiation configuration form.
215    * @param string $type
216    *   The language type to generate the table for.
217    */
218   protected function configureFormTable(array &$form, $type) {
219     $info = $form['#language_types_info'][$type];
220
221     $table_form = [
222       '#title' => $this->t('@type language detection', ['@type' => $info['name']]),
223       '#tree' => TRUE,
224       '#description' => $info['description'],
225       '#language_negotiation_info' => [],
226       '#show_operations' => FALSE,
227       'weight' => ['#tree' => TRUE],
228     ];
229     // Only show configurability checkbox for the unlocked language types.
230     if (empty($info['locked'])) {
231       $configurable = $this->languageTypes->get('configurable');
232       $table_form['configurable'] = [
233         '#type' => 'checkbox',
234         '#title' => $this->t('Customize %language_name language detection to differ from Interface text language detection settings', ['%language_name' => $info['name']]),
235         '#default_value' => in_array($type, $configurable),
236         '#attributes' => ['class' => ['language-customization-checkbox']],
237         '#attached' => [
238           'library' => [
239             'language/drupal.language.admin'
240           ],
241         ],
242       ];
243     }
244
245     $negotiation_info = $form['#language_negotiation_info'];
246     $enabled_methods = $this->languageTypes->get('negotiation.' . $type . '.enabled') ?: [];
247     $methods_weight = $this->languageTypes->get('negotiation.' . $type . '.method_weights') ?: [];
248
249     // Add missing data to the methods lists.
250     foreach ($negotiation_info as $method_id => $method) {
251       if (!isset($methods_weight[$method_id])) {
252         $methods_weight[$method_id] = isset($method['weight']) ? $method['weight'] : 0;
253       }
254     }
255
256     // Order methods list by weight.
257     asort($methods_weight);
258
259     foreach ($methods_weight as $method_id => $weight) {
260       // A language method might be no more available if the defining module has
261       // been disabled after the last configuration saving.
262       if (!isset($negotiation_info[$method_id])) {
263         continue;
264       }
265
266       $enabled = isset($enabled_methods[$method_id]);
267       $method = $negotiation_info[$method_id];
268
269       // List the method only if the current type is defined in its 'types' key.
270       // If it is not defined default to all the configurable language types.
271       $types = array_flip(isset($method['types']) ? $method['types'] : $form['#language_types']);
272
273       if (isset($types[$type])) {
274         $table_form['#language_negotiation_info'][$method_id] = $method;
275         $method_name = $method['name'];
276
277         $table_form['weight'][$method_id] = [
278           '#type' => 'weight',
279           '#title' => $this->t('Weight for @title language detection method', ['@title' => Unicode::strtolower($method_name)]),
280           '#title_display' => 'invisible',
281           '#default_value' => $weight,
282           '#attributes' => ['class' => ["language-method-weight-$type"]],
283           '#delta' => 20,
284         ];
285
286         $table_form['title'][$method_id] = ['#plain_text' => $method_name];
287
288         $table_form['enabled'][$method_id] = [
289           '#type' => 'checkbox',
290           '#title' => $this->t('Enable @title language detection method', ['@title' => Unicode::strtolower($method_name)]),
291           '#title_display' => 'invisible',
292           '#default_value' => $enabled,
293         ];
294         if ($method_id === LanguageNegotiationSelected::METHOD_ID) {
295           $table_form['enabled'][$method_id]['#default_value'] = TRUE;
296           $table_form['enabled'][$method_id]['#attributes'] = ['disabled' => 'disabled'];
297         }
298
299         $table_form['description'][$method_id] = ['#markup' => $method['description']];
300
301         $config_op = [];
302         if (isset($method['config_route_name'])) {
303           $config_op['configure'] = [
304             'title' => $this->t('Configure'),
305             'url' => Url::fromRoute($method['config_route_name']),
306           ];
307           // If there is at least one operation enabled show the operation
308           // column.
309           $table_form['#show_operations'] = TRUE;
310         }
311         $table_form['operation'][$method_id] = [
312          '#type' => 'operations',
313          '#links' => $config_op,
314         ];
315       }
316     }
317     $form[$type] = $table_form;
318   }
319
320   /**
321    * Disables the language switcher blocks.
322    *
323    * @param array $language_types
324    *   An array containing all language types whose language switchers need to
325    *   be disabled.
326    */
327   protected function disableLanguageSwitcher(array $language_types) {
328     $theme = $this->themeHandler->getDefault();
329     $blocks = $this->blockStorage->loadByProperties(['theme' => $theme]);
330     foreach ($language_types as $language_type) {
331       foreach ($blocks as $block) {
332         if ($block->getPluginId() == 'language_block:' . $language_type) {
333           $block->delete();
334         }
335       }
336     }
337   }
338
339 }