Update core 8.3.0

This commit is contained in:
Rob Davies 2017-04-13 15:53:35 +01:00
parent da7a7918f8
commit cd7a898e66
6144 changed files with 132297 additions and 87747 deletions

View file

@ -19,33 +19,33 @@ use Drupal\Core\Template\Attribute;
*/
function template_preprocess_language_negotiation_configure_form(&$variables) {
$form =& $variables['form'];
$variables['language_types'] = array();
$variables['language_types'] = [];
foreach ($form['#language_types'] as $type) {
$header = array(
$header = [
t('Detection method'),
t('Description'),
t('Enabled'),
t('Weight'),
);
];
// If there is at least one operation enabled show the operation column.
if ($form[$type]['#show_operations']) {
$header[] = t('Operations');
}
$table = array(
$table = [
'#type' => 'table',
'#header' => $header,
'#attributes' => array('id' => 'language-negotiation-methods-' . $type),
'#tabledrag' => array(
array(
'#attributes' => ['id' => 'language-negotiation-methods-' . $type],
'#tabledrag' => [
[
'action' => 'order',
'relationship' => 'sibling',
'group' => 'language-method-weight-' . $type,
),
),
);
],
],
];
foreach ($form[$type]['title'] as $id => $element) {
// Do not take form control structures.
@ -53,11 +53,11 @@ function template_preprocess_language_negotiation_configure_form(&$variables) {
$table[$id]['#attributes']['class'][] = 'draggable';
$table[$id]['#weight'] = $element['#weight'];
$table[$id]['title'] = array(
$table[$id]['title'] = [
'#prefix' => '<strong>',
$form[$type]['title'][$id],
'#suffix' => '</strong>',
);
];
$table[$id]['description'] = $form[$type]['description'][$id];
$table[$id]['enabled'] = $form[$type]['enabled'][$id];
$table[$id]['weight'] = $form[$type]['weight'][$id];
@ -77,7 +77,7 @@ function template_preprocess_language_negotiation_configure_form(&$variables) {
$configurable = isset($form[$type]['configurable']) ? $form[$type]['configurable'] : NULL;
unset($form[$type]['configurable']);
$variables['language_types'][] = array(
$variables['language_types'][] = [
'type' => $type,
'title' => $form[$type]['#title'],
'description' => $form[$type]['#description'],
@ -85,7 +85,7 @@ function template_preprocess_language_negotiation_configure_form(&$variables) {
'table' => $table,
'children' => $form[$type],
'attributes' => new Attribute(),
);
];
// Prevent the type from rendering with the remaining form child elements.
unset($form[$type]);
}
@ -107,42 +107,42 @@ function template_preprocess_language_content_settings_table(&$variables) {
// Add a render element representing the bundle language settings table.
$element = $variables['element'];
$header = array(
array(
$header = [
[
'data' => $element['#bundle_label'],
'class' => array('bundle'),
),
array(
'class' => ['bundle'],
],
[
'data' => t('Configuration'),
'class' => array('operations'),
),
);
'class' => ['operations'],
],
];
$rows = array();
$rows = [];
foreach (Element::children($element) as $bundle) {
$rows[$bundle] = array(
'data' => array(
array(
'data' => array(
$rows[$bundle] = [
'data' => [
[
'data' => [
'#prefix' => '<label>',
'#suffix' => '</label>',
'#plain_text' => $element[$bundle]['settings']['#label'],
),
'class' => array('bundle'),
),
array(
],
'class' => ['bundle'],
],
[
'data' => $element[$bundle]['settings'],
'class' => array('operations'),
),
),
'class' => array('bundle-settings'),
);
'class' => ['operations'],
],
],
'class' => ['bundle-settings'],
];
}
$variables['title'] = $element['#title'];
$variables['build'] = array(
$variables['build'] = [
'#header' => $header,
'#rows' => $rows,
'#type' => 'table',
);
];
}

View file

@ -35,17 +35,17 @@
* @ingroup language_negotiation
*/
function hook_language_types_info() {
return array(
'custom_language_type' => array(
return [
'custom_language_type' => [
'name' => t('Custom language'),
'description' => t('A custom language type.'),
'locked' => FALSE,
),
'fixed_custom_language_type' => array(
],
'fixed_custom_language_type' => [
'locked' => TRUE,
'fixed' => array('custom_language_negotiation_method'),
),
);
'fixed' => ['custom_language_negotiation_method'],
],
];
}
/**

View file

@ -29,42 +29,42 @@ function language_help($route_name, RouteMatchInterface $route_match) {
case 'help.page.language':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('The Language module allows you to configure the languages used on your site, and provides information for the <a href=":content">Content Translation</a>, <a href=":interface">Interface Translation</a>, and <a href=":configuration">Configuration Translation</a> modules, if they are enabled. For more information, see the <a href=":doc_url">online documentation for the Language module</a>.', array(':doc_url' => 'https://www.drupal.org/documentation/modules/language', ':content' => (\Drupal::moduleHandler()->moduleExists('content_translation')) ? \Drupal::url('help.page', array('name' => 'content_translation')) : '#', ':interface' => (\Drupal::moduleHandler()->moduleExists('locale')) ? \Drupal::url('help.page', array('name' => 'locale')) : '#', ':configuration' => (\Drupal::moduleHandler()->moduleExists('config_translation')) ? \Drupal::url('help.page', array('name' => 'config_translation')) : '#')) . '</p>';
$output .= '<p>' . t('The Language module allows you to configure the languages used on your site, and provides information for the <a href=":content">Content Translation</a>, <a href=":interface">Interface Translation</a>, and <a href=":configuration">Configuration Translation</a> modules, if they are enabled. For more information, see the <a href=":doc_url">online documentation for the Language module</a>.', [':doc_url' => 'https://www.drupal.org/documentation/modules/language', ':content' => (\Drupal::moduleHandler()->moduleExists('content_translation')) ? \Drupal::url('help.page', ['name' => 'content_translation']) : '#', ':interface' => (\Drupal::moduleHandler()->moduleExists('locale')) ? \Drupal::url('help.page', ['name' => 'locale']) : '#', ':configuration' => (\Drupal::moduleHandler()->moduleExists('config_translation')) ? \Drupal::url('help.page', ['name' => 'config_translation']) : '#']) . '</p>';
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Adding languages') . '</dt>';
$output .= '<dd>' . t('You can add languages on the <a href=":language_list">Languages</a> page by selecting <em>Add language</em> and choosing a language from the drop-down menu. This language is then displayed in the languages list, where it can be configured further. If the <a href=":interface">Interface translation module</a> is enabled, and the <em>translation server</em> is set as a translation source, then the interface translation for this language is automatically downloaded as well.', array(':language_list' => \Drupal::url('entity.configurable_language.collection'), ':interface' => (\Drupal::moduleHandler()->moduleExists('locale')) ? \Drupal::url('help.page', array('name' => 'locale')) : '#')) . '</dd>';
$output .= '<dd>' . t('You can add languages on the <a href=":language_list">Languages</a> page by selecting <em>Add language</em> and choosing a language from the drop-down menu. This language is then displayed in the languages list, where it can be configured further. If the <a href=":interface">Interface translation module</a> is enabled, and the <em>translation server</em> is set as a translation source, then the interface translation for this language is automatically downloaded as well.', [':language_list' => \Drupal::url('entity.configurable_language.collection'), ':interface' => (\Drupal::moduleHandler()->moduleExists('locale')) ? \Drupal::url('help.page', ['name' => 'locale']) : '#']) . '</dd>';
$output .= '<dt>' . t('Adding custom languages') . '</dt>';
$output .= '<dd>' . t('You can add a language that is not provided in the drop-down list by choosing <em>Custom language</em> at the end of the list. You then have to configure its language code, name, and direction in the form provided.') . '</dd>';
$output .= '<dt>' . t('Configuring content languages') . '</dt>';
$output .= '<dd>' . t('By default, content is created in the site\'s default language and no language selector is displayed on content creation pages. On the <a href=":content_language">Content language</a> page you can customize the language configuration for any supported content entity on your site (for example for content types or menu links). After choosing an entity, you are provided with a drop-down menu to set the default language and a check-box to display language selectors.', array(':content_language' => \Drupal::url('language.content_settings_page'))) . '</dd>';
$output .= '<dd>' . t('By default, content is created in the site\'s default language and no language selector is displayed on content creation pages. On the <a href=":content_language">Content language</a> page you can customize the language configuration for any supported content entity on your site (for example for content types or menu links). After choosing an entity, you are provided with a drop-down menu to set the default language and a check-box to display language selectors.', [':content_language' => \Drupal::url('language.content_settings_page')]) . '</dd>';
$output .= '<dt>' . t('Adding a language switcher block') . '</dt>';
$output .= '<dd>' . t('If the Block module is enabled, then you can add a language switcher block on the <a href=":blocks">Block layout</a> page to allow users to switch between languages.', array(':blocks' => (\Drupal::moduleHandler()->moduleExists('block')) ? \Drupal::url('block.admin_display') : '#')) . '</dd>';
$output .= '<dd>' . t('If the Block module is enabled, then you can add a language switcher block on the <a href=":blocks">Block layout</a> page to allow users to switch between languages.', [':blocks' => (\Drupal::moduleHandler()->moduleExists('block')) ? \Drupal::url('block.admin_display') : '#']) . '</dd>';
$output .= '<dt>' . t('Making a block visible per language') . '</dt>';
$output .= '<dd>' . t('If the Block module is enabled, then the Language module allows you to set the visibility of a block based on selected languages on the <a href=":blocks">Block layout</a> page.', array(':blocks' => (\Drupal::moduleHandler()->moduleExists('block')) ? \Drupal::url('block.admin_display') : '#')) . '</dd>';
$output .= '<dd>' . t('If the Block module is enabled, then the Language module allows you to set the visibility of a block based on selected languages on the <a href=":blocks">Block layout</a> page.', [':blocks' => (\Drupal::moduleHandler()->moduleExists('block')) ? \Drupal::url('block.admin_display') : '#']) . '</dd>';
$output .= '<dt>' . t('Choosing user languages') . '</dt>';
$output .= '<dd>' . t('Users can choose a <em>Site language</em> on their profile page. This language is used for email messages, and can be used by modules to determine a user\'s language. It can also be used for interface text, if the <em>User</em> method is enabled as a <em>Detection and selection</em> method (see below). Administrative users can choose a separate <em>Administration pages language</em> for the interface text on administration pages. This configuration is only available on the user\'s profile page if the <em>Account administration pages</em> method is enabled (see below).') . '</dd>';
$output .= '<dt>' . t('Language detection and selection') . '</dt>';
$output .= '<dd>' . t('The <a href=":detection">Detection and selection</a> page provides several methods for deciding which language is used for displaying interface text. When a method detects and selects an interface language, then the following methods in the list are not applied. You can order them by importance, with your preferred method at the top of the list, followed by one or several fall-back methods.', array(':detection' => \Drupal::url('language.negotiation')));
$output .= '<dd>' . t('The <a href=":detection">Detection and selection</a> page provides several methods for deciding which language is used for displaying interface text. When a method detects and selects an interface language, then the following methods in the list are not applied. You can order them by importance, with your preferred method at the top of the list, followed by one or several fall-back methods.', [':detection' => \Drupal::url('language.negotiation')]);
$output .= '<ul><li>' . t('<em>URL</em> sets the interface language based on a path prefix or domain (for example specifying <em>de</em> for German would result in URLs like <em>example.com/de/contact</em>). The default language does not require a path prefix, but can have one assigned as well. If the language detection is done by domain name, a domain needs to be specified for each language.') . '</li>';
$output .= '<li>' . t('<em>Session</em> determines the interface language from a request or session parameter (for example <em>example.com?language=de</em> would set the interface language to German based on the use of <em>de</em> as the <em>language</em> parameter).') . '</li>';
$output .= '<li>' . t('<em>User</em> follows the language configuration set on the user\'s profile page.') . '</li>';
$output .= '<li>' . t('<em>Browser</em> sets the interface language based on the browser\'s language settings. Since browsers use different language codes to refer to the same languages, you can add and edit languages codes to map the browser language codes to the <a href=":language_list">language codes</a> used on your site.', array(':language_list' => \Drupal::url('entity.configurable_language.collection'))) . '</li>';
$output .= '<li>' . t('<em>Browser</em> sets the interface language based on the browser\'s language settings. Since browsers use different language codes to refer to the same languages, you can add and edit languages codes to map the browser language codes to the <a href=":language_list">language codes</a> used on your site.', [':language_list' => \Drupal::url('entity.configurable_language.collection')]) . '</li>';
$output .= '<li>' . t('<em>Account administration pages</em> follows the configuration set as <em>Administration pages language</em> on the profile page of an administrative user. This method is similar to the <em>User</em> method, but only sets the interface text language on administration pages, independent of the interface text language on other pages.') . '</li>';
$output .= '<li>' . t('<em>Selected language</em> allows you to specify the site\'s default language or a specific language as the fall-back language. This method should be listed last.') . '</li></ul></dd>';
$output .= '</dl>';
return $output;
case 'entity.configurable_language.collection':
$output = '<p>' . t('Reorder the configured languages to set their order in the language switcher block and, when editing content, in the list of selectable languages. This ordering does not impact <a href=":detection">detection and selection</a>.', array(':detection' => \Drupal::url('language.negotiation'))) . '</p>';
$output .= '<p>' . t('The site default language can also be set. It is not recommended to change the default language on a working site. <a href=":language-detection">Configure the Selected language</a> setting on the detection and selection page to change the fallback language for language selection.', array(':language-detection' => \Drupal::url('language.negotiation'))) . '</p>';
$output = '<p>' . t('Reorder the configured languages to set their order in the language switcher block and, when editing content, in the list of selectable languages. This ordering does not impact <a href=":detection">detection and selection</a>.', [':detection' => \Drupal::url('language.negotiation')]) . '</p>';
$output .= '<p>' . t('The site default language can also be set. It is not recommended to change the default language on a working site. <a href=":language-detection">Configure the Selected language</a> setting on the detection and selection page to change the fallback language for language selection.', [':language-detection' => \Drupal::url('language.negotiation')]) . '</p>';
return $output;
case 'language.add':
return '<p>' . t('Add a language to be supported by your site. If your desired language is not available, pick <em>Custom language...</em> at the end and provide a language code and other details manually.') . '</p>';
case 'language.negotiation':
$output = '<p>' . t('Define how to decide which language is used to display page elements (primarily text provided by modules, such as field labels and help text). This decision is made by evaluating a series of detection methods for languages; the first detection method that gets a result will determine which language is used for that type of text. Be aware that some language detection methods are unreliable under certain conditions, such as browser detection when page-caching is enabled and a user is not currently logged in. Define the order of evaluation of language detection methods on this page. The default language can be changed in the <a href=":admin-change-language">list of languages</a>.', array(':admin-change-language' => \Drupal::url('entity.configurable_language.collection'))) . '</p>';
$output = '<p>' . t('Define how to decide which language is used to display page elements (primarily text provided by modules, such as field labels and help text). This decision is made by evaluating a series of detection methods for languages; the first detection method that gets a result will determine which language is used for that type of text. Be aware that some language detection methods are unreliable under certain conditions, such as browser detection when page-caching is enabled and a user is not currently logged in. Define the order of evaluation of language detection methods on this page. The default language can be changed in the <a href=":admin-change-language">list of languages</a>.', [':admin-change-language' => \Drupal::url('entity.configurable_language.collection')]) . '</p>';
return $output;
case 'language.negotiation_session':
@ -72,11 +72,11 @@ function language_help($route_name, RouteMatchInterface $route_match) {
return $output;
case 'language.negotiation_browser':
$output = '<p>' . t('Browsers use different language codes to refer to the same languages. Internally, a best effort is made to determine the correct language based on the code that the browser sends. You can add and edit additional mappings from browser language codes to <a href=":configure-languages">site languages</a>.', array(':configure-languages' => \Drupal::url('entity.configurable_language.collection'))) . '</p>';
$output = '<p>' . t('Browsers use different language codes to refer to the same languages. Internally, a best effort is made to determine the correct language based on the code that the browser sends. You can add and edit additional mappings from browser language codes to <a href=":configure-languages">site languages</a>.', [':configure-languages' => \Drupal::url('entity.configurable_language.collection')]) . '</p>';
return $output;
case 'language.negotiation_selected':
$output = '<p>' . t('Changing the selected language here (and leaving this option as the last among the detection and selection options) is the easiest way to change the fallback language for the website, if you need to change how your site works by default (e.g., when using an empty path prefix or using the default domain). <a href=":admin-change-language">Changing the site\'s default language</a> itself might have other undesired side effects.', array(':admin-change-language' => \Drupal::url('entity.configurable_language.collection'))) . '</p>';
$output = '<p>' . t('Changing the selected language here (and leaving this option as the last among the detection and selection options) is the easiest way to change the fallback language for the website, if you need to change how your site works by default (e.g., when using an empty path prefix or using the default domain). <a href=":admin-change-language">Changing the site\'s default language</a> itself might have other undesired side effects.', [':admin-change-language' => \Drupal::url('entity.configurable_language.collection')]) . '</p>';
return $output;
case 'entity.block.edit_form':
@ -92,7 +92,7 @@ function language_help($route_name, RouteMatchInterface $route_match) {
break;
case 'language.content_settings_page':
return t('Change language settings for <em>content types</em>, <em>taxonomy vocabularies</em>, <em>user profiles</em>, or any other supported element on your site. By default, language settings hide the language selector and the language is the site\'s default language.');
return '<p>' . t("Change language settings for <em>content types</em>, <em>taxonomy vocabularies</em>, <em>user profiles</em>, or any other supported element on your site. By default, language settings hide the language selector and the language is the site's default language.") . '</p>';
}
}
@ -100,16 +100,16 @@ function language_help($route_name, RouteMatchInterface $route_match) {
* Implements hook_theme().
*/
function language_theme() {
return array(
'language_negotiation_configure_form' => array(
return [
'language_negotiation_configure_form' => [
'render element' => 'form',
'file' => 'language.admin.inc',
),
'language_content_settings_table' => array(
],
'language_content_settings_table' => [
'render element' => 'element',
'file' => 'language.admin.inc',
),
);
],
];
}
/**
@ -123,18 +123,18 @@ function language_element_info_alter(&$type) {
// field.
if (isset($type['language_select'])) {
if (!isset($type['language_select']['#process'])) {
$type['language_select']['#process'] = array();
$type['language_select']['#process'] = [];
}
if (!isset($type['language_select']['#theme_wrappers'])) {
$type['language_select']['#theme_wrappers'] = array();
$type['language_select']['#theme_wrappers'] = [];
}
$type['language_select']['#process'] = array_merge($type['language_select']['#process'], array(
$type['language_select']['#process'] = array_merge($type['language_select']['#process'], [
'language_process_language_select',
array('Drupal\Core\Render\Element\Select', 'processSelect'),
array('Drupal\Core\Render\Element\RenderElement', 'processAjaxForm'),
));
['Drupal\Core\Render\Element\Select', 'processSelect'],
['Drupal\Core\Render\Element\RenderElement', 'processAjaxForm'],
]);
$type['language_select']['#theme'] = 'select';
$type['language_select']['#theme_wrappers'] = array_merge($type['language_select']['#theme_wrappers'], array('form_element'));
$type['language_select']['#theme_wrappers'] = array_merge($type['language_select']['#theme_wrappers'], ['form_element']);
$type['language_select']['#languages'] = LanguageInterface::STATE_CONFIGURABLE;
$type['language_select']['#multiple'] = FALSE;
}
@ -146,16 +146,16 @@ function language_element_info_alter(&$type) {
* @param array $element
* The form element to process.
*
* @return array $element
* @return array
* The processed form element.
*/
function language_process_language_select($element) {
// Don't set the options if another module (translation for example) already
// set the options.
if (!isset($element['#options'])) {
$element['#options'] = array();
$element['#options'] = [];
foreach (\Drupal::languageManager()->getLanguages($element['#languages']) as $langcode => $language) {
$element['#options'][$langcode] = $language->isLocked() ? t('- @name -', array('@name' => $language->getName())) : $language->getName();
$element['#options'][$langcode] = $language->isLocked() ? t('- @name -', ['@name' => $language->getName()]) : $language->getName();
}
}
return $element;
@ -168,7 +168,7 @@ function language_entity_base_field_info_alter(&$fields) {
foreach ($fields as $definition) {
// Set configurable form display for language fields with display options.
if ($definition->getType() == 'language') {
foreach (array('form', 'view') as $type) {
foreach (['form', 'view'] as $type) {
if ($definition->getDisplayOptions($type)) {
// The related configurations will be purged manually on Language
// module uninstallation. @see language_modules_uninstalled().
@ -201,8 +201,8 @@ function language_configuration_element_submit(&$form, FormStateInterface $form_
}
}
$config = ContentLanguageSettings::loadByEntityTypeBundle($entity_type_id, $bundle);
$config->setDefaultLangcode($form_state->getValue(array($element_name, 'langcode')));
$config->setLanguageAlterable($form_state->getValue(array($element_name, 'language_alterable')));
$config->setDefaultLangcode($form_state->getValue([$element_name, 'langcode']));
$config->setLanguageAlterable($form_state->getValue([$element_name, 'language_alterable']));
$config->save();
// Set the form_state languaged with the updated bundle.
@ -325,7 +325,7 @@ function language_modules_installed($modules) {
// display definitions to make language fields display configurable. Since
// this is not a hard dependency, and thus is not detected by the config
// system, we have to clean up the related values manually.
foreach (array('entity_view_display', 'entity_form_display') as $key) {
foreach (['entity_view_display', 'entity_form_display'] as $key) {
$displays = \Drupal::entityManager()->getStorage($key)->loadMultiple();
/** @var \Drupal\Core\Entity\Display\EntityDisplayInterface $display */
foreach ($displays as $display) {
@ -393,7 +393,7 @@ function language_preprocess_block(&$variables) {
function language_get_browser_drupal_langcode_mappings() {
$config = \Drupal::config('language.mappings');
if ($config->isNew()) {
return array();
return [];
}
return $config->get('map');
}
@ -462,7 +462,7 @@ function language_tour_tips_alter(array &$tour_tips, EntityInterface $entity) {
}
elseif ($tour_tip->get('id') == 'language-continue') {
$additional_continue = '';
$additional_modules = array();
$additional_modules = [];
if (!Drupal::service('module_handler')->moduleExists('locale')) {
$additional_modules[] = Drupal::service('module_handler')->getName('locale');
}

View file

@ -14,7 +14,7 @@ services:
- { name: event_subscriber }
language.config_factory_override:
class: Drupal\language\Config\LanguageConfigFactoryOverride
arguments: ['@config.storage', '@event_dispatcher', '@config.typed']
arguments: ['@config.storage', '@event_dispatcher', '@config.typed', '@language.default']
tags:
- { name: config.factory.override, priority: -254 }
- { name: event_subscriber }

View file

@ -68,11 +68,16 @@ class LanguageConfigFactoryOverride extends ConfigFactoryOverrideBase implements
* An event dispatcher instance to use for configuration events.
* @param \Drupal\Core\Config\TypedConfigManagerInterface $typed_config
* The typed configuration manager.
* @param \Drupal\Core\Language\LanguageDefault $default_language
* The default language.
*/
public function __construct(StorageInterface $storage, EventDispatcherInterface $event_dispatcher, TypedConfigManagerInterface $typed_config) {
public function __construct(StorageInterface $storage, EventDispatcherInterface $event_dispatcher, TypedConfigManagerInterface $typed_config, LanguageDefault $default_language) {
$this->baseStorage = $storage;
$this->eventDispatcher = $event_dispatcher;
$this->typedConfigManager = $typed_config;
// Prior to negiotiation the override language should be the default
// language.
$this->language = $default_language->get();
}
/**
@ -83,7 +88,7 @@ class LanguageConfigFactoryOverride extends ConfigFactoryOverrideBase implements
$storage = $this->getStorage($this->language->getId());
return $storage->readMultiple($names);
}
return array();
return [];
}
/**

View file

@ -36,6 +36,10 @@ interface LanguageConfigFactoryOverrideInterface extends ConfigFactoryOverrideIn
* The default language.
*
* @return $this
*
* @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0. This
* method has been replaced by injecting the default language into the
* constructor.
*/
public function setLanguageFromDefault(LanguageDefault $language_default = NULL);

View file

@ -71,7 +71,7 @@ class LanguageConfigOverride extends StorableConfigBase {
* {@inheritdoc}
*/
public function delete() {
$this->data = array();
$this->data = [];
$this->storage->delete($this->name);
Cache::invalidateTags($this->getCacheTags());
$this->isNew = TRUE;

View file

@ -168,7 +168,7 @@ class ConfigurableLanguageManager extends LanguageManager implements Configurabl
*/
protected function loadLanguageTypesConfiguration() {
if (!$this->languageTypes) {
$this->languageTypes = $this->configFactory->get('language.types')->get() ?: array('configurable' => array(), 'all' => parent::getLanguageTypes());
$this->languageTypes = $this->configFactory->get('language.types')->get() ?: ['configurable' => [], 'all' => parent::getLanguageTypes()];
}
return $this->languageTypes;
}
@ -227,7 +227,7 @@ class ConfigurableLanguageManager extends LanguageManager implements Configurabl
// afterwards. This can happen for instance while parsing negotiation
// method definitions.
elseif ($type == LanguageInterface::TYPE_INTERFACE) {
return new Language(array('id' => LanguageInterface::LANGCODE_SYSTEM));
return new Language(['id' => LanguageInterface::LANGCODE_SYSTEM]);
}
}
}
@ -241,11 +241,11 @@ class ConfigurableLanguageManager extends LanguageManager implements Configurabl
public function reset($type = NULL) {
if (!isset($type)) {
$this->initialized = FALSE;
$this->negotiatedLanguages = array();
$this->negotiatedMethods = array();
$this->negotiatedLanguages = [];
$this->negotiatedMethods = [];
$this->languageTypes = NULL;
$this->languageTypesInfo = NULL;
$this->languages = array();
$this->languages = [];
if ($this->negotiator) {
$this->negotiator->reset();
}
@ -270,7 +270,7 @@ class ConfigurableLanguageManager extends LanguageManager implements Configurabl
public function setNegotiator(LanguageNegotiatorInterface $negotiator) {
$this->negotiator = $negotiator;
$this->initialized = FALSE;
$this->negotiatedLanguages = array();
$this->negotiatedLanguages = [];
}
/**
@ -292,7 +292,7 @@ class ConfigurableLanguageManager extends LanguageManager implements Configurabl
// and the configuration entities for languages are not yet fully
// imported.
$default = $this->getDefaultLanguage();
$languages = array($default->getId() => $default);
$languages = [$default->getId() => $default];
$languages += $this->getDefaultLockedLanguages($default->getWeight());
// Load configurable languages on top of the defaults. Ideally this could
@ -325,7 +325,7 @@ class ConfigurableLanguageManager extends LanguageManager implements Configurabl
*/
public function getNativeLanguages() {
$languages = $this->getLanguages(LanguageInterface::STATE_CONFIGURABLE);
$natives = array();
$natives = [];
$original_language = $this->getConfigOverrideLanguage();
@ -363,9 +363,9 @@ class ConfigurableLanguageManager extends LanguageManager implements Configurabl
/**
* {@inheritdoc}
*/
public function getFallbackCandidates(array $context = array()) {
public function getFallbackCandidates(array $context = []) {
if ($this->isMultilingual()) {
$candidates = array();
$candidates = [];
if (empty($context['operation']) || $context['operation'] != 'locale_lookup') {
// If the fallback context is not locale_lookup, initialize the
// candidates with languages ordered by weight and add
@ -379,13 +379,13 @@ class ConfigurableLanguageManager extends LanguageManager implements Configurabl
// The first candidate should always be the desired language if
// specified.
if (!empty($context['langcode'])) {
$candidates = array($context['langcode'] => $context['langcode']) + $candidates;
$candidates = [$context['langcode'] => $context['langcode']] + $candidates;
}
}
// Let other modules hook in and add/change candidates.
$type = 'language_fallback_candidates';
$types = array();
$types = [];
if (!empty($context['operation'])) {
$types[] = $type . '_' . $context['operation'];
}
@ -414,8 +414,8 @@ class ConfigurableLanguageManager extends LanguageManager implements Configurabl
if (!empty($result)) {
// Allow modules to provide translations for specific links.
$this->moduleHandler->alter('language_switch_links', $result, $type, $path);
$links = (object) array('links' => $result, 'method_id' => $method_id);
$this->moduleHandler->alter('language_switch_links', $result, $type, $url);
$links = (object) ['links' => $result, 'method_id' => $method_id];
break;
}
}

View file

@ -77,7 +77,7 @@ interface ConfigurableLanguageManagerInterface extends LanguageManagerInterface
* @param string $langcode
* The language code for the override.
*
* @return \Drupal\Core\Config\StorageInterface $storage
* @return \Drupal\Core\Config\StorageInterface
* A storage object to use for reading and writing the
* configuration override.
*/

View file

@ -29,7 +29,7 @@ class DefaultLanguageItem extends LanguageItem {
$langcode = $this->getDefaultLangcode($entity);
}
// Always notify otherwise default langcode will not be set correctly.
$this->setValue(array('value' => $langcode), TRUE);
$this->setValue(['value' => $langcode], TRUE);
return $this;
}

View file

@ -7,7 +7,7 @@ use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Render\Element\FormElement;
/**
* Provides language element configuration.
* Defines an element for language configuration for a single field.
*
* @FormElement("language_configuration")
*/
@ -18,50 +18,50 @@ class LanguageConfiguration extends FormElement {
*/
public function getInfo() {
$class = get_class($this);
return array(
return [
'#input' => TRUE,
'#tree' => TRUE,
'#process' => array(
array($class, 'processLanguageConfiguration'),
),
);
'#process' => [
[$class, 'processLanguageConfiguration'],
],
];
}
/**
* Process handler for the language_configuration form element.
*/
public static function processLanguageConfiguration(&$element, FormStateInterface $form_state, &$form) {
$options = isset($element['#options']) ? $element['#options'] : array();
$options = isset($element['#options']) ? $element['#options'] : [];
// Avoid validation failure since we are moving the '#options' key in the
// nested 'language' select element.
unset($element['#options']);
/** @var \Drupal\language\Entity\ContentLanguageSettings $default_config */
$default_config = $element['#default_value'];
$element['langcode'] = array(
$element['langcode'] = [
'#type' => 'select',
'#title' => t('Default language'),
'#options' => $options + static::getDefaultOptions(),
'#description' => t('Explanation of the language options is found on the <a href=":languages_list_page">languages list page</a>.', array(':languages_list_page' => \Drupal::url('entity.configurable_language.collection'))),
'#description' => t('Explanation of the language options is found on the <a href=":languages_list_page">languages list page</a>.', [':languages_list_page' => \Drupal::url('entity.configurable_language.collection')]),
'#default_value' => ($default_config != NULL) ? $default_config->getDefaultLangcode() : LanguageInterface::LANGCODE_SITE_DEFAULT,
);
];
$element['language_alterable'] = array(
$element['language_alterable'] = [
'#type' => 'checkbox',
'#title' => t('Show language selector on create and edit pages'),
'#default_value' => ($default_config != NULL) ? $default_config->isLanguageAlterable() : FALSE,
);
];
// Add the entity type and bundle information to the form if they are set.
// They will be used, in the submit handler, to generate the names of the
// configuration entities that will store the settings and are a way to uniquely
// identify the entity.
$language = $form_state->get('language') ?: [];
$language += array(
$element['#name'] => array(
$language += [
$element['#name'] => [
'entity_type' => $element['#entity_information']['entity_type'],
'bundle' => $element['#entity_information']['bundle'],
),
);
],
];
$form_state->set('language', $language);
// Do not add the submit callback for the language content settings page,
@ -89,15 +89,15 @@ class LanguageConfiguration extends FormElement {
* An array containing the default options.
*/
protected static function getDefaultOptions() {
$language_options = array(
LanguageInterface::LANGCODE_SITE_DEFAULT => t("Site's default language (@language)", array('@language' => static::languageManager()->getDefaultLanguage()->getName())),
$language_options = [
LanguageInterface::LANGCODE_SITE_DEFAULT => t("Site's default language (@language)", ['@language' => static::languageManager()->getDefaultLanguage()->getName()]),
'current_interface' => t('Interface text language selected for page'),
'authors_default' => t("Author's preferred language"),
);
];
$languages = static::languageManager()->getLanguages(LanguageInterface::STATE_ALL);
foreach ($languages as $langcode => $language) {
$language_options[$langcode] = $language->isLocked() ? t('- @name -', array('@name' => $language->getName())) : $language->getName();
$language_options[$langcode] = $language->isLocked() ? t('- @name -', ['@name' => $language->getName()]) : $language->getName();
}
return $language_options;

View file

@ -246,18 +246,18 @@ class ConfigurableLanguage extends ConfigEntityBase implements ConfigurableLangu
if (!isset($standard_languages[$langcode])) {
// Drupal does not know about this language, so we set its values with the
// best guess. The user will be able to edit afterwards.
return static::create(array(
return static::create([
'id' => $langcode,
'label' => $langcode,
));
]);
}
else {
// A known predefined language, details will be filled in properly.
return static::create(array(
return static::create([
'id' => $langcode,
'label' => $standard_languages[$langcode][0],
'direction' => isset($standard_languages[$langcode][2]) ? $standard_languages[$langcode][2] : static::DIRECTION_LTR,
));
]);
}
}

View file

@ -140,8 +140,8 @@ class ConfigSubscriber implements EventSubscriberInterface {
/**
* {@inheritdoc}
*/
static function getSubscribedEvents() {
$events[ConfigEvents::SAVE][] = array('onConfigSave', 0);
public static function getSubscribedEvents() {
$events[ConfigEvents::SAVE][] = ['onConfigSave', 0];
return $events;
}

View file

@ -64,16 +64,14 @@ class LanguageRequestSubscriber implements EventSubscriberInterface {
}
/**
* Sets the request on the language manager.
* Sets the default language and initializes configuration overrides.
*
* @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
* The Event to process.
*/
public function onKernelRequestLanguage(GetResponseEvent $event) {
if ($event->getRequestType() == HttpKernelInterface::MASTER_REQUEST) {
$request = $event->getRequest();
$this->negotiator->setCurrentUser($this->currentUser);
$this->negotiator->reset();
if ($this->languageManager instanceof ConfigurableLanguageManagerInterface) {
$this->languageManager->setNegotiator($this->negotiator);
$this->languageManager->setConfigOverrideLanguage($this->languageManager->getCurrentLanguage());
@ -91,8 +89,8 @@ class LanguageRequestSubscriber implements EventSubscriberInterface {
* @return array
* An array of event listener definitions.
*/
static function getSubscribedEvents() {
$events[KernelEvents::REQUEST][] = array('onKernelRequestLanguage', 255);
public static function getSubscribedEvents() {
$events[KernelEvents::REQUEST][] = ['onKernelRequestLanguage', 255];
return $events;
}

View file

@ -52,11 +52,11 @@ class ContentLanguageSettingsForm extends FormBase {
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$entity_types = $this->entityManager->getDefinitions();
$labels = array();
$default = array();
$labels = [];
$default = [];
$bundles = $this->entityManager->getAllBundleInfo();
$language_configuration = array();
$language_configuration = [];
foreach ($entity_types as $entity_type_id => $entity_type) {
if (!$entity_type instanceof ContentEntityTypeInterface || !$entity_type->hasKey('langcode') || !isset($bundles[$entity_type_id])) {
continue;
@ -76,65 +76,65 @@ class ContentLanguageSettingsForm extends FormBase {
asort($labels);
$form = array(
$form = [
'#labels' => $labels,
'#attached' => array(
'library' => array(
'#attached' => [
'library' => [
'language/drupal.language.admin',
),
),
'#attributes' => array(
],
],
'#attributes' => [
'class' => 'language-content-settings-form',
),
);
],
];
$form['entity_types'] = array(
$form['entity_types'] = [
'#title' => $this->t('Custom language settings'),
'#type' => 'checkboxes',
'#options' => $labels,
'#default_value' => $default,
);
];
$form['settings'] = array('#tree' => TRUE);
$form['settings'] = ['#tree' => TRUE];
foreach ($labels as $entity_type_id => $label) {
$entity_type = $entity_types[$entity_type_id];
$form['settings'][$entity_type_id] = array(
$form['settings'][$entity_type_id] = [
'#title' => $label,
'#type' => 'container',
'#entity_type' => $entity_type_id,
'#theme' => 'language_content_settings_table',
'#bundle_label' => $entity_type->getBundleLabel() ?: $label,
'#states' => array(
'visible' => array(
':input[name="entity_types[' . $entity_type_id . ']"]' => array('checked' => TRUE),
),
),
);
'#states' => [
'visible' => [
':input[name="entity_types[' . $entity_type_id . ']"]' => ['checked' => TRUE],
],
],
];
foreach ($bundles[$entity_type_id] as $bundle => $bundle_info) {
$form['settings'][$entity_type_id][$bundle]['settings'] = array(
$form['settings'][$entity_type_id][$bundle]['settings'] = [
'#type' => 'item',
'#label' => $bundle_info['label'],
'language' => array(
'language' => [
'#type' => 'language_configuration',
'#entity_information' => array(
'#entity_information' => [
'entity_type' => $entity_type_id,
'bundle' => $bundle,
),
],
'#default_value' => $language_configuration[$entity_type_id][$bundle],
),
);
],
];
}
}
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = array(
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Save configuration'),
'#button_type' => 'primary',
);
];
return $form;
}
@ -143,9 +143,13 @@ class ContentLanguageSettingsForm extends FormBase {
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$entity_types = $form_state->getValue('entity_types');
foreach ($form_state->getValue('settings') as $entity_type => $entity_settings) {
foreach ($entity_settings as $bundle => $bundle_settings) {
$config = ContentLanguageSettings::loadByEntityTypeBundle($entity_type, $bundle);
if (empty($entity_types[$entity_type])) {
$bundle_settings['settings']['language']['language_alterable'] = FALSE;
}
$config->setDefaultLangcode($bundle_settings['settings']['language']['langcode'])
->setLanguageAlterable($bundle_settings['settings']['language']['language_alterable'])
->save();

View file

@ -30,50 +30,50 @@ class LanguageAddForm extends LanguageFormBase {
$predefined_languages['custom'] = $this->t('Custom language...');
$predefined_default = $form_state->getValue('predefined_langcode', key($predefined_languages));
$form['predefined_langcode'] = array(
$form['predefined_langcode'] = [
'#type' => 'select',
'#title' => $this->t('Language name'),
'#default_value' => $predefined_default,
'#options' => $predefined_languages,
);
$form['predefined_submit'] = array(
];
$form['predefined_submit'] = [
'#type' => 'submit',
'#value' => $this->t('Add language'),
'#name' => 'add_language',
'#limit_validation_errors' => array(array('predefined_langcode'), array('predefined_submit')),
'#states' => array(
'invisible' => array(
'select#edit-predefined-langcode' => array('value' => 'custom'),
),
),
'#validate' => array('::validatePredefined'),
'#submit' => array('::submitForm', '::save'),
'#limit_validation_errors' => [['predefined_langcode'], ['predefined_submit']],
'#states' => [
'invisible' => [
'select#edit-predefined-langcode' => ['value' => 'custom'],
],
],
'#validate' => ['::validatePredefined'],
'#submit' => ['::submitForm', '::save'],
'#button_type' => 'primary',
);
];
$custom_language_states_conditions = array(
'select#edit-predefined-langcode' => array('value' => 'custom'),
);
$form['custom_language'] = array(
$custom_language_states_conditions = [
'select#edit-predefined-langcode' => ['value' => 'custom'],
];
$form['custom_language'] = [
'#type' => 'container',
'#states' => array(
'#states' => [
'visible' => $custom_language_states_conditions,
),
);
],
];
$this->commonForm($form['custom_language']);
$form['custom_language']['langcode']['#states'] = array(
$form['custom_language']['langcode']['#states'] = [
'required' => $custom_language_states_conditions,
);
$form['custom_language']['label']['#states'] = array(
];
$form['custom_language']['label']['#states'] = [
'required' => $custom_language_states_conditions,
);
$form['custom_language']['submit'] = array(
];
$form['custom_language']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Add custom language'),
'#name' => 'add_custom_language',
'#validate' => array('::validateCustom'),
'#submit' => array('::submitForm', '::save'),
);
'#validate' => ['::validateCustom'],
'#submit' => ['::submitForm', '::save'],
];
return $form;
}
@ -84,14 +84,14 @@ class LanguageAddForm extends LanguageFormBase {
public function save(array $form, FormStateInterface $form_state) {
parent::save($form, $form_state);
$t_args = array('%language' => $this->entity->label(), '%langcode' => $this->entity->id());
$t_args = ['%language' => $this->entity->label(), '%langcode' => $this->entity->id()];
$this->logger('language')->notice('The %language (%langcode) language has been created.', $t_args);
drupal_set_message($this->t('The language %language has been created and can now be used.', $t_args));
if ($this->moduleHandler->moduleExists('block')) {
// Tell the user they have the option to add a language switcher block
// to their theme so they can switch between the languages.
drupal_set_message($this->t('Use one of the language switcher blocks to allow site visitors to switch between languages. You can enable these blocks on the <a href=":block-admin">block administration page</a>.', array(':block-admin' => $this->url('block.admin_display'))));
drupal_set_message($this->t('Use one of the language switcher blocks to allow site visitors to switch between languages. You can enable these blocks on the <a href=":block-admin">block administration page</a>.', [':block-admin' => $this->url('block.admin_display')]));
}
$form_state->setRedirectUrl($this->entity->urlInfo('collection'));
}
@ -101,7 +101,7 @@ class LanguageAddForm extends LanguageFormBase {
*/
public function actions(array $form, FormStateInterface $form_state) {
// No actions needed.
return array();
return [];
}
/**
@ -114,7 +114,7 @@ class LanguageAddForm extends LanguageFormBase {
$this->validateCommon($form['custom_language'], $form_state);
if ($language = $this->languageManager->getLanguage($langcode)) {
$form_state->setErrorByName('langcode', $this->t('The language %language (%langcode) already exists.', array('%language' => $language->getName(), '%langcode' => $langcode)));
$form_state->setErrorByName('langcode', $this->t('The language %language (%langcode) already exists.', ['%language' => $language->getName(), '%langcode' => $langcode]));
}
}
else {
@ -132,7 +132,7 @@ class LanguageAddForm extends LanguageFormBase {
}
else {
if ($language = $this->languageManager->getLanguage($langcode)) {
$form_state->setErrorByName('predefined_langcode', $this->t('The language %language (%langcode) already exists.', array('%language' => $language->getName(), '%langcode' => $langcode)));
$form_state->setErrorByName('predefined_langcode', $this->t('The language %language (%langcode) already exists.', ['%language' => $language->getName(), '%langcode' => $langcode]));
}
}
}

View file

@ -27,14 +27,14 @@ class LanguageDeleteForm extends EntityDeleteForm {
* {@inheritdoc}
*/
protected function getDeletionMessage() {
return $this->t('The %language (%langcode) language has been removed.', array('%language' => $this->entity->label(), '%langcode' => $this->entity->id()));
return $this->t('The %language (%langcode) language has been removed.', ['%language' => $this->entity->label(), '%langcode' => $this->entity->id()]);
}
/**
* {@inheritdoc}
*/
public function logDeletionMessage() {
$this->logger('language')->notice('The %language (%langcode) language has been removed.', array('%language' => $this->entity->label(), '%langcode' => $this->entity->id()));
$this->logger('language')->notice('The %language (%langcode) language has been removed.', ['%language' => $this->entity->label(), '%langcode' => $this->entity->id()]);
}
}

View file

@ -29,12 +29,12 @@ class LanguageEditForm extends LanguageFormBase {
* {@inheritdoc}
*/
public function actions(array $form, FormStateInterface $form_state) {
$actions['submit'] = array(
$actions['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Save language'),
'#validate' => array('::validateCommon'),
'#submit' => array('::submitForm', '::save'),
);
'#validate' => ['::validateCommon'],
'#submit' => ['::submitForm', '::save'],
];
return $actions;
}
@ -44,7 +44,7 @@ class LanguageEditForm extends LanguageFormBase {
public function save(array $form, FormStateInterface $form_state) {
parent::save($form, $form_state);
$form_state->setRedirectUrl($this->entity->urlInfo('collection'));
$this->logger('language')->notice('The %language (%langcode) language has been updated.', array('%language' => $this->entity->label(), '%langcode' => $this->entity->id()));
$this->logger('language')->notice('The %language (%langcode) language has been updated.', ['%language' => $this->entity->label(), '%langcode' => $this->entity->id()]);
}
}

View file

@ -47,45 +47,45 @@ abstract class LanguageFormBase extends EntityForm {
/* @var $language \Drupal\language\ConfigurableLanguageInterface */
$language = $this->entity;
if ($language->getId()) {
$form['langcode_view'] = array(
$form['langcode_view'] = [
'#type' => 'item',
'#title' => $this->t('Language code'),
'#markup' => $language->id()
);
$form['langcode'] = array(
];
$form['langcode'] = [
'#type' => 'value',
'#value' => $language->id()
);
];
}
else {
$form['langcode'] = array(
$form['langcode'] = [
'#type' => 'textfield',
'#title' => $this->t('Language code'),
'#maxlength' => 12,
'#required' => TRUE,
'#default_value' => '',
'#disabled' => FALSE,
'#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>', array(':w3ctags' => 'http://www.w3.org/International/articles/language-tags/')),
);
'#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/']),
];
}
$form['label'] = array(
$form['label'] = [
'#type' => 'textfield',
'#title' => $this->t('Language name'),
'#maxlength' => 64,
'#default_value' => $language->label(),
'#required' => TRUE,
);
$form['direction'] = array(
];
$form['direction'] = [
'#type' => 'radios',
'#title' => $this->t('Direction'),
'#required' => TRUE,
'#description' => $this->t('Direction that text in this language is presented.'),
'#default_value' => $language->getDirection(),
'#options' => array(
'#options' => [
LanguageInterface::DIRECTION_LTR => $this->t('Left to right'),
LanguageInterface::DIRECTION_RTL => $this->t('Right to left'),
),
);
],
];
return $form;
}
@ -96,13 +96,13 @@ abstract class LanguageFormBase extends EntityForm {
public function validateCommon(array $form, FormStateInterface $form_state) {
// Ensure sane field values for langcode and name.
if (!isset($form['langcode_view']) && !preg_match('@^[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$@', $form_state->getValue('langcode'))) {
$form_state->setErrorByName('langcode', $this->t('%field must be a valid language tag as <a href=":url">defined by the W3C</a>.', array(
$form_state->setErrorByName('langcode', $this->t('%field must be a valid language tag as <a href=":url">defined by the W3C</a>.', [
'%field' => $form['langcode']['#title'],
':url' => 'http://www.w3.org/International/articles/language-tags/',
)));
]));
}
if ($form_state->getValue('label') != Html::escape($form_state->getValue('label'))) {
$form_state->setErrorByName('label', $this->t('%field cannot contain any markup.', array('%field' => $form['label']['#title'])));
$form_state->setErrorByName('label', $this->t('%field cannot contain any markup.', ['%field' => $form['label']['#title']]));
}
}

View file

@ -32,7 +32,7 @@ class NegotiationBrowserDeleteForm extends ConfirmFormBase {
* {@inheritdoc}
*/
public function getQuestion() {
return $this->t('Are you sure you want to delete %browser_langcode?', array('%browser_langcode' => $this->browserLangcode));
return $this->t('Are you sure you want to delete %browser_langcode?', ['%browser_langcode' => $this->browserLangcode]);
}
/**
@ -68,9 +68,9 @@ class NegotiationBrowserDeleteForm extends ConfirmFormBase {
->clear('map.' . $this->browserLangcode)
->save();
$args = array(
$args = [
'%browser' => $this->browserLangcode,
);
];
$this->logger('language')->notice('The browser language detection mapping for the %browser browser language code has been deleted.', $args);

View file

@ -60,12 +60,12 @@ class NegotiationBrowserForm extends ConfigFormBase {
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form = array();
$form = [];
// Initialize a language list to the ones available, including English.
$languages = $this->languageManager->getLanguages();
$existing_languages = array();
$existing_languages = [];
foreach ($languages as $langcode => $language) {
$existing_languages[$langcode] = $language->getName();
}
@ -77,10 +77,10 @@ class NegotiationBrowserForm extends ConfigFormBase {
$language_options = $this->languageManager->getStandardLanguageListWithoutConfigured();
}
else {
$language_options = array(
$language_options = [
(string) $this->t('Existing languages') => $existing_languages,
(string) $this->t('Languages not yet added') => $this->languageManager->getStandardLanguageListWithoutConfigured(),
);
];
}
$form['mappings'] = [
@ -96,24 +96,24 @@ class NegotiationBrowserForm extends ConfigFormBase {
$mappings = $this->language_get_browser_drupal_langcode_mappings();
foreach ($mappings as $browser_langcode => $drupal_langcode) {
$form['mappings'][$browser_langcode] = array(
'browser_langcode' => array(
$form['mappings'][$browser_langcode] = [
'browser_langcode' => [
'#title' => $this->t('Browser language code'),
'#title_display' => 'invisible',
'#type' => 'textfield',
'#default_value' => $browser_langcode,
'#size' => 20,
'#required' => TRUE,
),
'drupal_langcode' => array(
],
'drupal_langcode' => [
'#title' => $this->t('Site language'),
'#title_display' => 'invisible',
'#type' => 'select',
'#options' => $language_options,
'#default_value' => $drupal_langcode,
'#required' => TRUE,
),
);
],
];
// Operations column.
$form['mappings'][$browser_langcode]['operations'] = [
'#type' => 'operations',
@ -126,22 +126,22 @@ class NegotiationBrowserForm extends ConfigFormBase {
}
// Add empty row.
$form['new_mapping'] = array(
$form['new_mapping'] = [
'#type' => 'details',
'#title' => $this->t('Add a new mapping'),
'#tree' => TRUE,
);
$form['new_mapping']['browser_langcode'] = array(
];
$form['new_mapping']['browser_langcode'] = [
'#type' => 'textfield',
'#title' => $this->t('Browser language code'),
'#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>', array(':w3ctags' => 'http://www.w3.org/International/articles/language-tags/')),
'#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/']),
'#size' => 20,
);
$form['new_mapping']['drupal_langcode'] = array(
];
$form['new_mapping']['drupal_langcode'] = [
'#type' => 'select',
'#title' => $this->t('Site language'),
'#options' => $language_options,
);
];
return parent::buildForm($form, $form_state);
}
@ -151,7 +151,7 @@ class NegotiationBrowserForm extends ConfigFormBase {
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
// Array to check if all browser language codes are unique.
$unique_values = array();
$unique_values = [];
// Check all mappings.
if ($form_state->hasValue('mappings')) {
@ -207,7 +207,7 @@ class NegotiationBrowserForm extends ConfigFormBase {
protected function language_get_browser_drupal_langcode_mappings() {
$config = $this->config('language.mappings');
if ($config->isNew()) {
return array();
return [];
}
return $config->get('map');
}

View file

@ -124,12 +124,12 @@ class NegotiationConfigureForm extends ConfigFormBase {
public function buildForm(array $form, FormStateInterface $form_state) {
$configurable = $this->languageTypes->get('configurable');
$form = array(
$form = [
'#theme' => 'language_negotiation_configure_form',
'#language_types_info' => $this->languageManager->getDefinedLanguageTypesInfo(),
'#language_negotiation_info' => $this->negotiator->getNegotiationMethods(),
);
$form['#language_types'] = array();
];
$form['#language_types'] = [];
foreach ($form['#language_types_info'] as $type => $info) {
// Show locked language types only if they are configurable.
@ -142,12 +142,12 @@ class NegotiationConfigureForm extends ConfigFormBase {
$this->configureFormTable($form, $type);
}
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
$form['actions'] = ['#type' => 'actions'];
$form['actions']['submit'] = [
'#type' => 'submit',
'#button_type' => 'primary',
'#value' => $this->t('Save settings'),
);
];
return $form;
}
@ -159,17 +159,17 @@ class NegotiationConfigureForm extends ConfigFormBase {
$configurable_types = $form['#language_types'];
$stored_values = $this->languageTypes->get('configurable');
$customized = array();
$method_weights_type = array();
$customized = [];
$method_weights_type = [];
foreach ($configurable_types as $type) {
$customized[$type] = in_array($type, $stored_values);
$method_weights = array();
$enabled_methods = $form_state->getValue(array($type, 'enabled'));
$method_weights = [];
$enabled_methods = $form_state->getValue([$type, 'enabled']);
$enabled_methods[LanguageNegotiationSelected::METHOD_ID] = TRUE;
$method_weights_input = $form_state->getValue(array($type, 'weight'));
if ($form_state->hasValue(array($type, 'configurable'))) {
$customized[$type] = !$form_state->isValueEmpty(array($type, 'configurable'));
$method_weights_input = $form_state->getValue([$type, 'weight']);
if ($form_state->hasValue([$type, 'configurable'])) {
$customized[$type] = !$form_state->isValueEmpty([$type, 'configurable']);
}
foreach ($method_weights_input as $method_id => $weight) {
@ -216,33 +216,33 @@ class NegotiationConfigureForm extends ConfigFormBase {
protected function configureFormTable(array &$form, $type) {
$info = $form['#language_types_info'][$type];
$table_form = array(
'#title' => $this->t('@type language detection', array('@type' => $info['name'])),
$table_form = [
'#title' => $this->t('@type language detection', ['@type' => $info['name']]),
'#tree' => TRUE,
'#description' => $info['description'],
'#language_negotiation_info' => array(),
'#language_negotiation_info' => [],
'#show_operations' => FALSE,
'weight' => array('#tree' => TRUE),
);
'weight' => ['#tree' => TRUE],
];
// Only show configurability checkbox for the unlocked language types.
if (empty($info['locked'])) {
$configurable = $this->languageTypes->get('configurable');
$table_form['configurable'] = array(
$table_form['configurable'] = [
'#type' => 'checkbox',
'#title' => $this->t('Customize %language_name language detection to differ from Interface text language detection settings', array('%language_name' => $info['name'])),
'#title' => $this->t('Customize %language_name language detection to differ from Interface text language detection settings', ['%language_name' => $info['name']]),
'#default_value' => in_array($type, $configurable),
'#attributes' => array('class' => array('language-customization-checkbox')),
'#attached' => array(
'library' => array(
'#attributes' => ['class' => ['language-customization-checkbox']],
'#attached' => [
'library' => [
'language/drupal.language.admin'
),
),
);
],
],
];
}
$negotiation_info = $form['#language_negotiation_info'];
$enabled_methods = $this->languageTypes->get('negotiation.' . $type . '.enabled') ?: array();
$methods_weight = $this->languageTypes->get('negotiation.' . $type . '.method_weights') ?: array();
$enabled_methods = $this->languageTypes->get('negotiation.' . $type . '.enabled') ?: [];
$methods_weight = $this->languageTypes->get('negotiation.' . $type . '.method_weights') ?: [];
// Add missing data to the methods lists.
foreach ($negotiation_info as $method_id => $method) {
@ -272,44 +272,44 @@ class NegotiationConfigureForm extends ConfigFormBase {
$table_form['#language_negotiation_info'][$method_id] = $method;
$method_name = $method['name'];
$table_form['weight'][$method_id] = array(
$table_form['weight'][$method_id] = [
'#type' => 'weight',
'#title' => $this->t('Weight for @title language detection method', array('@title' => Unicode::strtolower($method_name))),
'#title' => $this->t('Weight for @title language detection method', ['@title' => Unicode::strtolower($method_name)]),
'#title_display' => 'invisible',
'#default_value' => $weight,
'#attributes' => array('class' => array("language-method-weight-$type")),
'#attributes' => ['class' => ["language-method-weight-$type"]],
'#delta' => 20,
);
];
$table_form['title'][$method_id] = array('#plain_text' => $method_name);
$table_form['title'][$method_id] = ['#plain_text' => $method_name];
$table_form['enabled'][$method_id] = array(
$table_form['enabled'][$method_id] = [
'#type' => 'checkbox',
'#title' => $this->t('Enable @title language detection method', array('@title' => Unicode::strtolower($method_name))),
'#title' => $this->t('Enable @title language detection method', ['@title' => Unicode::strtolower($method_name)]),
'#title_display' => 'invisible',
'#default_value' => $enabled,
);
];
if ($method_id === LanguageNegotiationSelected::METHOD_ID) {
$table_form['enabled'][$method_id]['#default_value'] = TRUE;
$table_form['enabled'][$method_id]['#attributes'] = array('disabled' => 'disabled');
$table_form['enabled'][$method_id]['#attributes'] = ['disabled' => 'disabled'];
}
$table_form['description'][$method_id] = array('#markup' => $method['description']);
$table_form['description'][$method_id] = ['#markup' => $method['description']];
$config_op = array();
$config_op = [];
if (isset($method['config_route_name'])) {
$config_op['configure'] = array(
$config_op['configure'] = [
'title' => $this->t('Configure'),
'url' => Url::fromRoute($method['config_route_name']),
);
];
// If there is at least one operation enabled show the operation
// column.
$table_form['#show_operations'] = TRUE;
}
$table_form['operation'][$method_id] = array(
$table_form['operation'][$method_id] = [
'#type' => 'operations',
'#links' => $config_op,
);
];
}
}
$form[$type] = $table_form;
@ -324,7 +324,7 @@ class NegotiationConfigureForm extends ConfigFormBase {
*/
protected function disableLanguageSwitcher(array $language_types) {
$theme = $this->themeHandler->getDefault();
$blocks = $this->blockStorage->loadByProperties(array('theme' => $theme));
$blocks = $this->blockStorage->loadByProperties(['theme' => $theme]);
foreach ($language_types as $language_type) {
foreach ($blocks as $block) {
if ($block->getPluginId() == 'language_block:' . $language_type) {

View file

@ -30,12 +30,12 @@ class NegotiationSelectedForm extends ConfigFormBase {
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('language.negotiation');
$form['selected_langcode'] = array(
$form['selected_langcode'] = [
'#type' => 'language_select',
'#title' => $this->t('Language'),
'#languages' => LanguageInterface::STATE_CONFIGURABLE | LanguageInterface::STATE_SITE_DEFAULT,
'#default_value' => $config->get('selected_langcode'),
);
];
return parent::buildForm($form, $form_state);
}

View file

@ -29,12 +29,12 @@ class NegotiationSessionForm extends ConfigFormBase {
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('language.negotiation');
$form['language_negotiation_session_param'] = array(
$form['language_negotiation_session_param'] = [
'#title' => $this->t('Request/session parameter'),
'#type' => 'textfield',
'#default_value' => $config->get('session.parameter'),
'#description' => $this->t('Name of the request/session parameter used to determine the desired language.'),
);
];
$form_state->setRedirect('language.negotiation');

View file

@ -66,63 +66,63 @@ class NegotiationUrlForm extends ConfigFormBase {
global $base_url;
$config = $this->config('language.negotiation');
$form['language_negotiation_url_part'] = array(
$form['language_negotiation_url_part'] = [
'#title' => $this->t('Part of the URL that determines language'),
'#type' => 'radios',
'#options' => array(
'#options' => [
LanguageNegotiationUrl::CONFIG_PATH_PREFIX => $this->t('Path prefix'),
LanguageNegotiationUrl::CONFIG_DOMAIN => $this->t('Domain'),
),
],
'#default_value' => $config->get('url.source'),
);
];
$form['prefix'] = array(
$form['prefix'] = [
'#type' => 'details',
'#tree' => TRUE,
'#title' => $this->t('Path prefix configuration'),
'#open' => TRUE,
'#description' => $this->t('Language codes or other custom text to use as a path prefix for URL language detection. For the selected fallback language, this value may be left blank. <strong>Modifying this value may break existing URLs. Use with caution in a production environment.</strong> Example: Specifying "deutsch" as the path prefix code for German results in URLs like "example.com/deutsch/contact".'),
'#states' => array(
'visible' => array(
':input[name="language_negotiation_url_part"]' => array(
'#states' => [
'visible' => [
':input[name="language_negotiation_url_part"]' => [
'value' => (string) LanguageNegotiationUrl::CONFIG_PATH_PREFIX,
),
),
),
);
$form['domain'] = array(
],
],
],
];
$form['domain'] = [
'#type' => 'details',
'#tree' => TRUE,
'#title' => $this->t('Domain configuration'),
'#open' => TRUE,
'#description' => $this->t('The domain names to use for these languages. <strong>Modifying this value may break existing URLs. Use with caution in a production environment.</strong> Example: Specifying "de.example.com" as language domain for German will result in a URL like "http://de.example.com/contact".'),
'#states' => array(
'visible' => array(
':input[name="language_negotiation_url_part"]' => array(
'#states' => [
'visible' => [
':input[name="language_negotiation_url_part"]' => [
'value' => (string) LanguageNegotiationUrl::CONFIG_DOMAIN,
),
),
),
);
],
],
],
];
$languages = $this->languageManager->getLanguages();
$prefixes = $config->get('url.prefixes');
$domains = $config->get('url.domains');
foreach ($languages as $langcode => $language) {
$t_args = array('%language' => $language->getName(), '%langcode' => $language->getId());
$form['prefix'][$langcode] = array(
$t_args = ['%language' => $language->getName(), '%langcode' => $language->getId()];
$form['prefix'][$langcode] = [
'#type' => 'textfield',
'#title' => $language->isDefault() ? $this->t('%language (%langcode) path prefix (Default language)', $t_args) : $this->t('%language (%langcode) path prefix', $t_args),
'#maxlength' => 64,
'#default_value' => isset($prefixes[$langcode]) ? $prefixes[$langcode] : '',
'#field_prefix' => $base_url . '/',
);
$form['domain'][$langcode] = array(
];
$form['domain'][$langcode] = [
'#type' => 'textfield',
'#title' => $this->t('%language (%langcode) domain', array('%language' => $language->getName(), '%langcode' => $language->getId())),
'#title' => $this->t('%language (%langcode) domain', ['%language' => $language->getName(), '%langcode' => $language->getId()]),
'#maxlength' => 128,
'#default_value' => isset($domains[$langcode]) ? $domains[$langcode] : '',
);
];
}
$form_state->setRedirect('language.negotiation');
@ -143,7 +143,7 @@ class NegotiationUrlForm extends ConfigFormBase {
$default_langcode = $this->languageManager->getDefaultLanguage()->getId();
}
foreach ($languages as $langcode => $language) {
$value = $form_state->getValue(array('prefix', $langcode));
$value = $form_state->getValue(['prefix', $langcode]);
if ($value === '') {
if (!($default_langcode == $langcode) && $form_state->getValue('language_negotiation_url_part') == LanguageNegotiationUrl::CONFIG_PATH_PREFIX) {
// Throw a form error if the prefix is blank for a non-default language,
@ -161,35 +161,35 @@ class NegotiationUrlForm extends ConfigFormBase {
elseif (isset($count[$value]) && $count[$value] > 1) {
// Throw a form error if there are two languages with the same
// domain/prefix.
$form_state->setErrorByName("prefix][$langcode", $this->t('The prefix for %language, %value, is not unique.', array('%language' => $language->getName(), '%value' => $value)));
$form_state->setErrorByName("prefix][$langcode", $this->t('The prefix for %language, %value, is not unique.', ['%language' => $language->getName(), '%value' => $value]));
}
}
// Count repeated values for uniqueness check.
$count = array_count_values($form_state->getValue('domain'));
foreach ($languages as $langcode => $language) {
$value = $form_state->getValue(array('domain', $langcode));
$value = $form_state->getValue(['domain', $langcode]);
if ($value === '') {
if ($form_state->getValue('language_negotiation_url_part') == LanguageNegotiationUrl::CONFIG_DOMAIN) {
// Throw a form error if the domain is blank for a non-default language,
// although it is required for selected negotiation type.
$form_state->setErrorByName("domain][$langcode", $this->t('The domain may not be left blank for %language.', array('%language' => $language->getName())));
$form_state->setErrorByName("domain][$langcode", $this->t('The domain may not be left blank for %language.', ['%language' => $language->getName()]));
}
}
elseif (isset($count[$value]) && $count[$value] > 1) {
// Throw a form error if there are two languages with the same
// domain/domain.
$form_state->setErrorByName("domain][$langcode", $this->t('The domain for %language, %value, is not unique.', array('%language' => $language->getName(), '%value' => $value)));
$form_state->setErrorByName("domain][$langcode", $this->t('The domain for %language, %value, is not unique.', ['%language' => $language->getName(), '%value' => $value]));
}
}
// Domain names should not contain protocol and/or ports.
foreach ($languages as $langcode => $language) {
$value = $form_state->getValue(array('domain', $langcode));
$value = $form_state->getValue(['domain', $langcode]);
if (!empty($value)) {
// Ensure we have exactly one protocol when checking the hostname.
$host = 'http://' . str_replace(array('http://', 'https://'), '', $value);
$host = 'http://' . str_replace(['http://', 'https://'], '', $value);
if (parse_url($host, PHP_URL_HOST) != $value) {
$form_state->setErrorByName("domain][$langcode", $this->t('The domain for %language may only contain the domain name, not a trailing slash, protocol and/or port.', ['%language' => $language->getName()]));
}

View file

@ -102,7 +102,7 @@ class PathProcessorLanguage implements InboundPathProcessorInterface, OutboundPa
/**
* {@inheritdoc}
*/
public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
public function processOutbound($path, &$options = [], Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
if (!isset($this->multilingual)) {
$this->multilingual = $this->languageManager->isMultilingual();
}
@ -131,7 +131,7 @@ class PathProcessorLanguage implements InboundPathProcessorInterface, OutboundPa
*/
protected function initProcessors($scope) {
$interface = '\Drupal\Core\PathProcessor\\' . Unicode::ucfirst($scope) . 'PathProcessorInterface';
$this->processors[$scope] = array();
$this->processors[$scope] = [];
$weights = [];
foreach ($this->languageManager->getLanguageTypes() as $type) {
foreach ($this->negotiator->getNegotiationMethods($type) as $method_id => $method) {
@ -174,7 +174,7 @@ class PathProcessorLanguage implements InboundPathProcessorInterface, OutboundPa
* Resets the collected processors instances.
*/
public function reset() {
$this->processors = array();
$this->processors = [];
}
}

View file

@ -19,6 +19,9 @@ class LanguageAccessControlHandler extends EntityAccessControlHandler {
*/
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
switch ($operation) {
case 'view':
return parent::checkAccess($entity, $operation, $account);
case 'update':
/* @var \Drupal\Core\Language\LanguageInterface $entity */
return AccessResult::allowedIf(!$entity->isLocked())->addCacheableDependency($entity)

View file

@ -71,11 +71,11 @@ class LanguageListBuilder extends DraggableListBuilder {
* {@inheritdoc}
*/
public function load() {
$entities = $this->storage->loadByProperties(array('locked' => FALSE));
$entities = $this->storage->loadByProperties(['locked' => FALSE]);
// Sort the entities using the entity class's sort() method.
// See \Drupal\Core\Config\Entity\ConfigEntityBase::sort().
uasort($entities, array($this->entityType->getClass(), 'sort'));
uasort($entities, [$this->entityType->getClass(), 'sort']);
return $entities;
}
@ -90,10 +90,10 @@ class LanguageListBuilder extends DraggableListBuilder {
* {@inheritdoc}
*/
public function buildHeader() {
$header = array(
$header = [
'label' => t('Name'),
'default' => t('Default'),
) + parent::buildHeader();
] + parent::buildHeader();
return $header;
}
@ -102,14 +102,14 @@ class LanguageListBuilder extends DraggableListBuilder {
*/
public function buildRow(EntityInterface $entity) {
$row['label'] = $entity->label();
$row['default'] = array(
$row['default'] = [
'#type' => 'radio',
'#parents' => array('site_default_language'),
'#title' => t('Set @title as default', array('@title' => $entity->label())),
'#parents' => ['site_default_language'],
'#title' => t('Set @title as default', ['@title' => $entity->label()]),
'#title_display' => 'invisible',
'#return_value' => $entity->id(),
'#id' => 'edit-site-default-language-' . $entity->id(),
);
];
// Mark the right language as default in the form.
if ($entity->id() == $this->languageManager->getDefaultLanguage()->getId()) {
$row['default']['#default_value'] = $entity->id();
@ -157,7 +157,7 @@ class LanguageListBuilder extends DraggableListBuilder {
drupal_set_message(t('Configuration saved.'));
// Force the redirection to the page with the language we have just
// selected as default.
$form_state->setRedirectUrl($this->entities[$new_id]->urlInfo('collection', array('language' => $this->entities[$new_id])));
$form_state->setRedirectUrl($this->entities[$new_id]->urlInfo('collection', ['language' => $this->entities[$new_id]]));
}
}

View file

@ -68,7 +68,7 @@ class LanguageNegotiator implements LanguageNegotiatorInterface {
*
* @var \Drupal\Core\Language\LanguageInterface[]
*/
protected $negotiatedLanguages = array();
protected $negotiatedLanguages = [];
/**
* Constructs a new LanguageNegotiator object.
@ -105,8 +105,8 @@ class LanguageNegotiator implements LanguageNegotiatorInterface {
* {@inheritdoc}
*/
public function reset() {
$this->negotiatedLanguages = array();
$this->methods = array();
$this->negotiatedLanguages = [];
$this->methods = [];
}
/**
@ -150,7 +150,7 @@ class LanguageNegotiator implements LanguageNegotiatorInterface {
$method_id = static::METHOD_ID;
}
return array($method_id => $language);
return [$method_id => $language];
}
/**
@ -163,7 +163,7 @@ class LanguageNegotiator implements LanguageNegotiatorInterface {
* An array of enabled detection methods for the provided language type.
*/
protected function getEnabledNegotiators($type) {
return $this->configFactory->get('language.types')->get('negotiation.' . $type . '.enabled') ?: array();
return $this->configFactory->get('language.types')->get('negotiation.' . $type . '.enabled') ?: [];
}
/**
@ -207,7 +207,7 @@ class LanguageNegotiator implements LanguageNegotiatorInterface {
*/
public function getNegotiationMethodInstance($method_id) {
if (!isset($this->methods[$method_id])) {
$instance = $this->negotiatorManager->createInstance($method_id, array());
$instance = $this->negotiatorManager->createInstance($method_id, []);
$instance->setLanguageManager($this->languageManager);
$instance->setConfig($this->configFactory);
$instance->setCurrentUser($this->currentUser);
@ -229,7 +229,7 @@ class LanguageNegotiator implements LanguageNegotiatorInterface {
*/
public function isNegotiationMethodEnabled($method_id, $type = NULL) {
$enabled = FALSE;
$language_types = !empty($type) ? array($type) : $this->languageManager->getLanguageTypes();
$language_types = !empty($type) ? [$type] : $this->languageManager->getLanguageTypes();
foreach ($language_types as $type) {
$enabled_methods = $this->getEnabledNegotiators($type);
@ -245,7 +245,7 @@ class LanguageNegotiator implements LanguageNegotiatorInterface {
/**
* {@inheritdoc}
*/
function saveConfiguration($type, $enabled_methods) {
public function saveConfiguration($type, $enabled_methods) {
// As configurable language types might have changed, we reset the cache.
$this->languageManager->reset();
$definitions = $this->getNegotiationMethods();
@ -274,7 +274,7 @@ class LanguageNegotiator implements LanguageNegotiatorInterface {
/**
* {@inheritdoc}
*/
function purgeConfiguration() {
public function purgeConfiguration() {
// Ensure that we are getting the defined language negotiation information.
// An invocation of \Drupal\Core\Extension\ModuleInstaller::install() or
// \Drupal\Core\Extension\ModuleInstaller::uninstall() could invalidate the
@ -289,7 +289,7 @@ class LanguageNegotiator implements LanguageNegotiatorInterface {
/**
* {@inheritdoc}
*/
function updateConfiguration(array $types) {
public function updateConfiguration(array $types) {
// Ensure that we are getting the defined language negotiation information.
// An invocation of \Drupal\Core\Extension\ModuleInstaller::install() or
// \Drupal\Core\Extension\ModuleInstaller::uninstall() could invalidate the
@ -297,7 +297,7 @@ class LanguageNegotiator implements LanguageNegotiatorInterface {
$this->negotiatorManager->clearCachedDefinitions();
$this->languageManager->reset();
$language_types = array();
$language_types = [];
$language_types_info = $this->languageManager->getDefinedLanguageTypesInfo();
$method_definitions = $this->getNegotiationMethods();
@ -316,7 +316,7 @@ class LanguageNegotiator implements LanguageNegotiatorInterface {
// default language negotiation settings, we use the values
// negotiated for the interface language which, should always be
// available.
$method_weights = array(LanguageNegotiationUI::METHOD_ID);
$method_weights = [LanguageNegotiationUI::METHOD_ID];
$method_weights = array_flip($method_weights);
$this->saveConfiguration($type, $method_weights);
}
@ -330,7 +330,7 @@ class LanguageNegotiator implements LanguageNegotiatorInterface {
// If the language type is locked we can just store its default language
// negotiation settings if it has some, since it is not configurable.
if ($has_default_settings) {
$method_weights = array();
$method_weights = [];
// Default settings are in $info['fixed'].
foreach ($info['fixed'] as $weight => $method_id) {
@ -351,10 +351,10 @@ class LanguageNegotiator implements LanguageNegotiatorInterface {
}
// Store the language type configuration.
$config = array(
$config = [
'configurable' => array_keys(array_filter($language_types)),
'all' => array_keys($language_types),
);
];
$this->languageManager->saveLanguageTypesConfiguration($config);
}

View file

@ -187,12 +187,12 @@ interface LanguageNegotiatorInterface {
* @param int[] $enabled_methods
* An array of language negotiation method weights keyed by method ID.
*/
function saveConfiguration($type, $enabled_methods);
public function saveConfiguration($type, $enabled_methods);
/**
* Resave the configuration to purge missing negotiation methods.
*/
function purgeConfiguration();
public function purgeConfiguration();
/**
* Updates the configuration based on the given language types.
@ -204,6 +204,6 @@ interface LanguageNegotiatorInterface {
* @param string[] $types
* An array of configurable language types.
*/
function updateConfiguration(array $types);
public function updateConfiguration(array $types);
}

View file

@ -29,8 +29,8 @@ class LanguageServiceProvider extends ServiceProviderBase {
->addArgument(new Reference('current_user'));
$container->register('path_processor_language', 'Drupal\language\HttpKernel\PathProcessorLanguage')
->addTag('path_processor_inbound', array('priority' => 300))
->addTag('path_processor_outbound', array('priority' => 100))
->addTag('path_processor_inbound', ['priority' => 300])
->addTag('path_processor_outbound', ['priority' => 100])
->addArgument(new Reference('config.factory'))
->addArgument(new Reference('language_manager'))
->addArgument(new Reference('language_negotiator'))
@ -54,13 +54,6 @@ class LanguageServiceProvider extends ServiceProviderBase {
$container->setParameter('language.default_values', $default_language_values);
}
// For monolingual sites, we explicitly set the default language for the
// language config override service as there is no language negotiation.
if (!$this->isMultilingual()) {
$container->getDefinition('language.config_factory_override')
->addMethodCall('setLanguageFromDefault', array(new Reference('language.default')));
}
}
/**

View file

@ -84,22 +84,22 @@ class LanguageBlock extends BlockBase implements ContainerFactoryPluginInterface
* {@inheritdoc}
*/
public function build() {
$build = array();
$build = [];
$route_name = $this->pathMatcher->isFrontPage() ? '<front>' : '<current>';
$type = $this->getDerivativeId();
$links = $this->languageManager->getLanguageSwitchLinks($type, Url::fromRoute($route_name));
if (isset($links->links)) {
$build = array(
$build = [
'#theme' => 'links__language_block',
'#links' => $links->links,
'#attributes' => array(
'class' => array(
'#attributes' => [
'class' => [
"language-switcher-{$links->method_id}",
),
),
],
],
'#set_active_class' => TRUE,
);
];
}
return $build;
}

View file

@ -68,23 +68,23 @@ class Language extends ConditionPluginBase implements ContainerFactoryPluginInte
if ($this->languageManager->isMultilingual()) {
// Fetch languages.
$languages = $this->languageManager->getLanguages();
$langcodes_options = array();
$langcodes_options = [];
foreach ($languages as $language) {
$langcodes_options[$language->getId()] = $language->getName();
}
$form['langcodes'] = array(
$form['langcodes'] = [
'#type' => 'checkboxes',
'#title' => $this->t('Language selection'),
'#default_value' => $this->configuration['langcodes'],
'#options' => $langcodes_options,
'#description' => $this->t('Select languages to enforce. If none are selected, all languages will be allowed.'),
);
];
}
else {
$form['langcodes'] = array(
$form['langcodes'] = [
'#type' => 'value',
'#default_value' => $this->configuration['langcodes'],
);
];
}
return parent::buildConfigurationForm($form, $form_state);
}
@ -111,7 +111,7 @@ class Language extends ConditionPluginBase implements ContainerFactoryPluginInte
$result[$item->getId()] = $item->getName();
}
return $result;
}, array());
}, []);
// If we have more than one language selected, separate them by commas.
if (count($this->configuration['langcodes']) > 1) {
@ -122,9 +122,9 @@ class Language extends ConditionPluginBase implements ContainerFactoryPluginInte
$languages = array_pop($language_names);
}
if (!empty($this->configuration['negate'])) {
return t('The language is not @languages.', array('@languages' => $languages));
return t('The language is not @languages.', ['@languages' => $languages]);
}
return t('The language is @languages.', array('@languages' => $languages));
return t('The language is @languages.', ['@languages' => $languages]);
}
/**
@ -144,7 +144,7 @@ class Language extends ConditionPluginBase implements ContainerFactoryPluginInte
* {@inheritdoc}
*/
public function defaultConfiguration() {
return array('langcodes' => array()) + parent::defaultConfiguration();
return ['langcodes' => []] + parent::defaultConfiguration();
}
}

View file

@ -21,7 +21,7 @@ class LanguageBlock extends DeriverBase {
$configurable_types = $language_manager->getLanguageTypes();
foreach ($configurable_types as $type) {
$this->derivatives[$type] = $base_plugin_definition;
$this->derivatives[$type]['admin_label'] = t('Language switcher (@type)', array('@type' => $info[$type]['name']));
$this->derivatives[$type]['admin_label'] = t('Language switcher (@type)', ['@type' => $info[$type]['name']]);
}
// If there is just one configurable type then change the title of the
// block.

View file

@ -2,7 +2,6 @@
namespace Drupal\language\Plugin\LanguageNegotiation;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
@ -118,20 +117,8 @@ class LanguageNegotiationContentEntity extends LanguageNegotiationMethodBase imp
unset($options['language']);
}
if (isset($options['query']) && is_string($options['query'])) {
$query = [];
parse_str($options['query'], $query);
$options['query'] = $query;
}
else {
$options['query'] = [];
}
if (!isset($options['query'][static::QUERY_PARAMETER])) {
$query_addon = [static::QUERY_PARAMETER => $langcode];
$options['query'] += $query_addon;
// @todo Remove this once https://www.drupal.org/node/2507005 lands.
$path .= (strpos($path, '?') !== FALSE ? '&' : '?') . UrlHelper::buildQuery($query_addon);
$options['query'][static::QUERY_PARAMETER] = $langcode;
}
if ($bubbleable_metadata) {
@ -276,7 +263,7 @@ class LanguageNegotiationContentEntity extends LanguageNegotiationMethodBase imp
$this->contentEntityPaths = [];
$entity_types = $this->entityManager->getDefinitions();
foreach ($entity_types as $entity_type_id => $entity_type) {
if ($entity_type->isSubclassOf(ContentEntityInterface::class)) {
if ($entity_type->entityClassImplements(ContentEntityInterface::class)) {
$entity_paths = array_fill_keys($entity_type->getLinkTemplates(), $entity_type_id);
$this->contentEntityPaths = array_merge($this->contentEntityPaths, $entity_paths);
}

View file

@ -81,7 +81,7 @@ class LanguageNegotiationSession extends LanguageNegotiationMethodBase implement
/**
* {@inheritdoc}
*/
public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
public function processOutbound($path, &$options = [], Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
if ($request) {
// The following values are not supposed to change during a single page
// request processing.
@ -102,11 +102,6 @@ class LanguageNegotiationSession extends LanguageNegotiationMethodBase implement
// enabled, and the corresponding option has been set, we must preserve
// any explicit user language preference even with cookies disabled.
if ($this->queryRewrite) {
if (isset($options['query']) && is_string($options['query'])) {
$query = array();
parse_str($options['query'], $query);
$options['query'] = $query;
}
if (!isset($options['query'][$this->queryParam])) {
$options['query'][$this->queryParam] = $this->queryValue;
}
@ -129,24 +124,24 @@ class LanguageNegotiationSession extends LanguageNegotiationMethodBase implement
* {@inheritdoc}
*/
public function getLanguageSwitchLinks(Request $request, $type, Url $url) {
$links = array();
$links = [];
$config = $this->config->get('language.negotiation')->get('session');
$param = $config['parameter'];
$language_query = isset($_SESSION[$param]) ? $_SESSION[$param] : $this->languageManager->getCurrentLanguage($type)->getId();
$query = array();
$query = [];
parse_str($request->getQueryString(), $query);
foreach ($this->languageManager->getNativeLanguages() as $language) {
$langcode = $language->getId();
$links[$langcode] = array(
$links[$langcode] = [
// We need to clone the $url object to avoid using the same one for all
// links. When the links are rendered, options are set on the $url
// object, so if we use the same one, they would be set for all links.
'url' => clone $url,
'title' => $language->getName(),
'attributes' => array('class' => array('language-link')),
'attributes' => ['class' => ['language-link']],
'query' => $query,
);
];
if ($language_query != $langcode) {
$links[$langcode]['query'][$param] = $langcode;
}

View file

@ -80,7 +80,7 @@ class LanguageNegotiationUrl extends LanguageNegotiationMethodBase implements In
if (!empty($config['domains'][$language->getId()])) {
// Ensure that there is exactly one protocol in the URL when
// checking the hostname.
$host = 'http://' . str_replace(array('http://', 'https://'), '', $config['domains'][$language->getId()]);
$host = 'http://' . str_replace(['http://', 'https://'], '', $config['domains'][$language->getId()]);
$host = parse_url($host, PHP_URL_HOST);
if ($http_host == $host) {
$langcode = $language->getId();
@ -100,15 +100,18 @@ class LanguageNegotiationUrl extends LanguageNegotiationMethodBase implements In
*/
public function processInbound($path, Request $request) {
$config = $this->config->get('language.negotiation')->get('url');
$parts = explode('/', trim($path, '/'));
$prefix = array_shift($parts);
// Search prefix within added languages.
foreach ($this->languageManager->getLanguages() as $language) {
if (isset($config['prefixes'][$language->getId()]) && $config['prefixes'][$language->getId()] == $prefix) {
// Rebuild $path with the language removed.
$path = '/' . implode('/', $parts);
break;
if ($config['source'] == LanguageNegotiationUrl::CONFIG_PATH_PREFIX) {
$parts = explode('/', trim($path, '/'));
$prefix = array_shift($parts);
// Search prefix within added languages.
foreach ($this->languageManager->getLanguages() as $language) {
if (isset($config['prefixes'][$language->getId()]) && $config['prefixes'][$language->getId()] == $prefix) {
// Rebuild $path with the language removed.
$path = '/' . implode('/', $parts);
break;
}
}
}
@ -118,7 +121,7 @@ class LanguageNegotiationUrl extends LanguageNegotiationMethodBase implements In
/**
* {@inheritdoc}
*/
public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
public function processOutbound($path, &$options = [], Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
$url_scheme = 'http';
$port = 80;
if ($request) {
@ -151,7 +154,7 @@ class LanguageNegotiationUrl extends LanguageNegotiationMethodBase implements In
// retain it below.
if (!empty($options['base_url'])) {
// The colon in the URL scheme messes up the port checking below.
$normalized_base_url = str_replace(array('https://', 'http://'), '', $options['base_url']);
$normalized_base_url = str_replace(['https://', 'http://'], '', $options['base_url']);
}
// Ask for an absolute URL with our modified base URL.
@ -191,20 +194,20 @@ class LanguageNegotiationUrl extends LanguageNegotiationMethodBase implements In
* {@inheritdoc}
*/
public function getLanguageSwitchLinks(Request $request, $type, Url $url) {
$links = array();
$links = [];
$query = $request->query->all();
foreach ($this->languageManager->getNativeLanguages() as $language) {
$links[$language->getId()] = array(
$links[$language->getId()] = [
// We need to clone the $url object to avoid using the same one for all
// links. When the links are rendered, options are set on the $url
// object, so if we use the same one, they would be set for all links.
'url' => clone $url,
'title' => $language->getName(),
'language' => $language,
'attributes' => array('class' => array('language-link')),
'attributes' => ['class' => ['language-link']],
'query' => $query,
);
];
}
return $links;

View file

@ -19,7 +19,7 @@ class DefaultLangcode extends Config {
/**
* {@inheritdoc}
*/
public function import(Row $row, array $old_destination_id_values = array()) {
public function import(Row $row, array $old_destination_id_values = []) {
$destination = $row->getDestination();
$langcode = $destination['default_langcode'];

View file

@ -17,7 +17,7 @@ class Language extends DrupalSqlBase {
* {@inheritdoc}
*/
public function fields() {
return array(
return [
'language' => $this->t('The language code.'),
'name' => $this->t('The English name of the language.'),
'native' => $this->t('The native name of the language.'),
@ -29,18 +29,18 @@ class Language extends DrupalSqlBase {
'prefix' => $this->t('Path prefix used for this language.'),
'weight' => $this->t('The language weight when listed.'),
'javascript' => $this->t('Location of the JavaScript translation file.'),
);
];
}
/**
* {@inheritdoc}
*/
public function getIds() {
return array(
'language' => array(
return [
'language' => [
'type' => 'string',
),
);
],
];
}
/**

View file

@ -19,20 +19,20 @@ class LanguageContentSettings extends DrupalSqlBase {
*/
public function query() {
return $this->select('node_type', 't')
->fields('t', array(
->fields('t', [
'type',
));
]);
}
/**
* {@inheritdoc}
*/
public function fields() {
$fields = array(
$fields = [
'type' => $this->t('Type'),
'language_content_type' => $this->t('Multilingual support.'),
'i18n_lock_node' => $this->t('Lock language.'),
);
];
return $fields;
}

View file

@ -19,20 +19,20 @@ class LanguageContentSettings extends DrupalSqlBase {
*/
public function query() {
return $this->select('node_type', 't')
->fields('t', array(
->fields('t', [
'type',
));
]);
}
/**
* {@inheritdoc}
*/
public function fields() {
$fields = array(
$fields = [
'type' => $this->t('Type'),
'language_content_type' => $this->t('Multilingual support.'),
'i18n_lock_node' => $this->t('Lock language.'),
);
];
return $fields;
}

View file

@ -19,10 +19,10 @@ class EntityTypeWithoutLanguageFormTest extends WebTestBase {
*
* @var array
*/
public static $modules = array(
public static $modules = [
'language',
'language_test',
);
];
/**
* {@inheritdoc}
@ -31,9 +31,9 @@ class EntityTypeWithoutLanguageFormTest extends WebTestBase {
parent::setUp();
// Create and log in administrative user.
$admin_user = $this->drupalCreateUser(array(
$admin_user = $this->drupalCreateUser([
'administer languages',
));
]);
$this->drupalLogin($admin_user);
}

View file

@ -20,11 +20,11 @@ class LanguageConfigurationElementTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('taxonomy', 'node', 'language', 'language_elements_test', 'field_ui');
public static $modules = ['taxonomy', 'node', 'language', 'language_elements_test', 'field_ui'];
protected function setUp() {
parent::setUp();
$user = $this->drupalCreateUser(array('access administration pages', 'administer languages', 'administer content types'));
$user = $this->drupalCreateUser(['access administration pages', 'administer languages', 'administer content types']);
$this->drupalLogin($user);
}
@ -60,12 +60,12 @@ class LanguageConfigurationElementTest extends WebTestBase {
$this->assertFieldChecked('edit-lang-configuration-language-alterable');
// Test if content type settings have been saved.
$edit = array(
$edit = [
'name' => 'Page',
'type' => 'page',
'language_configuration[langcode]' => 'authors_default',
'language_configuration[language_alterable]' => TRUE,
);
];
$this->drupalPostForm('admin/structure/types/add', $edit, 'Save and manage fields');
// Make sure the settings are saved when creating the content type.
@ -80,11 +80,11 @@ class LanguageConfigurationElementTest extends WebTestBase {
*/
public function testDefaultLangcode() {
// Add some custom languages.
foreach (array('aa', 'bb', 'cc') as $language_code) {
ConfigurableLanguage::create(array(
foreach (['aa', 'bb', 'cc'] as $language_code) {
ConfigurableLanguage::create([
'id' => $language_code,
'label' => $this->randomMachineName(),
))->save();
])->save();
}
// Fixed language.
@ -154,14 +154,14 @@ class LanguageConfigurationElementTest extends WebTestBase {
// Create the article content type first if the profile used is not the
// standard one.
if ($this->profile != 'standard') {
$this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article'));
$this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']);
}
$admin_user = $this->drupalCreateUser(array('administer content types'));
$admin_user = $this->drupalCreateUser(['administer content types']);
$this->drupalLogin($admin_user);
$edit = array(
$edit = [
'language_configuration[langcode]' => 'current_interface',
'language_configuration[language_alterable]' => TRUE,
);
];
$this->drupalPostForm('admin/structure/types/manage/article', $edit, t('Save content type'));
// Check the language default configuration for the articles.
$configuration = ContentLanguageSettings::loadByEntityTypeBundle('node', 'article');
@ -169,9 +169,9 @@ class LanguageConfigurationElementTest extends WebTestBase {
$this->assertEqual($configuration->getDefaultLangcode(), 'current_interface', 'The default language configuration has been saved on the Article content type.');
$this->assertTrue($configuration->isLanguageAlterable(), 'The alterable language configuration has been saved on the Article content type.');
// Update the article content type by changing the title label.
$edit = array(
$edit = [
'title_label' => 'Name'
);
];
$this->drupalPostForm('admin/structure/types/manage/article', $edit, t('Save content type'));
// Check that we still have the settings for the updated node type.
$configuration = ContentLanguageSettings::loadByEntityTypeBundle('node', 'article');
@ -187,19 +187,19 @@ class LanguageConfigurationElementTest extends WebTestBase {
// Create the article content type first if the profile used is not the
// standard one.
if ($this->profile != 'standard') {
$this->drupalCreateContentType(array(
$this->drupalCreateContentType([
'type' => 'article',
'name' => 'Article'
));
]);
}
$admin_user = $this->drupalCreateUser(array('administer content types'));
$admin_user = $this->drupalCreateUser(['administer content types']);
$this->drupalLogin($admin_user);
// Create language configuration for the articles.
$edit = array(
$edit = [
'language_configuration[langcode]' => 'authors_default',
'language_configuration[language_alterable]' => TRUE,
);
];
$this->drupalPostForm('admin/structure/types/manage/article', $edit, t('Save content type'));
// Check the language default configuration for articles is present.
@ -207,7 +207,7 @@ class LanguageConfigurationElementTest extends WebTestBase {
$this->assertTrue($configuration, 'The language configuration is present.');
// Delete 'article' bundle.
$this->drupalPostForm('admin/structure/types/manage/article/delete', array(), t('Delete'));
$this->drupalPostForm('admin/structure/types/manage/article/delete', [], t('Delete'));
// Check that the language configuration has been deleted.
\Drupal::entityManager()->getStorage('language_content_settings')->resetCache();
@ -225,12 +225,12 @@ class LanguageConfigurationElementTest extends WebTestBase {
]);
$vocabulary->save();
$admin_user = $this->drupalCreateUser(array('administer taxonomy'));
$admin_user = $this->drupalCreateUser(['administer taxonomy']);
$this->drupalLogin($admin_user);
$edit = array(
$edit = [
'default_language[langcode]' => 'current_interface',
'default_language[language_alterable]' => TRUE,
);
];
$this->drupalPostForm('admin/structure/taxonomy/manage/country', $edit, t('Save'));
// Check the language default configuration.
@ -239,9 +239,9 @@ class LanguageConfigurationElementTest extends WebTestBase {
$this->assertEqual($configuration->getDefaultLangcode(), 'current_interface', 'The default language configuration has been saved on the Country vocabulary.');
$this->assertTrue($configuration->isLanguageAlterable(), 'The alterable language configuration has been saved on the Country vocabulary.');
// Update the vocabulary.
$edit = array(
$edit = [
'name' => 'Nation'
);
];
$this->drupalPostForm('admin/structure/taxonomy/manage/country', $edit, t('Save'));
// Check that we still have the settings for the updated vocabulary.
$configuration = ContentLanguageSettings::loadByEntityTypeBundle('taxonomy_term', 'country');

View file

@ -18,18 +18,18 @@ class LanguageConfigurationTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('language');
public static $modules = ['language'];
/**
* Functional tests for adding, editing and deleting languages.
*/
function testLanguageConfiguration() {
public function testLanguageConfiguration() {
// Ensure the after installing the language module the weight of the English
// language is still 0.
$this->assertEqual(ConfigurableLanguage::load('en')->getWeight(), 0, 'The English language has a weight of 0.');
// User to add and remove language.
$admin_user = $this->drupalCreateUser(array('administer languages', 'access administration pages'));
$admin_user = $this->drupalCreateUser(['administer languages', 'access administration pages']);
$this->drupalLogin($admin_user);
// Check if the Default English language has no path prefix.
@ -41,9 +41,9 @@ class LanguageConfigurationTest extends WebTestBase {
$this->assertFieldByXPath('//input[contains(@class, "button--primary")]', 'Add language', 'Add language is a primary button');
// Add predefined language.
$edit = array(
$edit = [
'predefined_langcode' => 'fr',
);
];
$this->drupalPostForm(NULL, $edit, 'Add language');
$this->assertText('French');
$this->assertUrl(\Drupal::url('entity.configurable_language.collection', [], ['absolute' => TRUE]), [], 'Correct page redirection.');
@ -63,9 +63,9 @@ class LanguageConfigurationTest extends WebTestBase {
$this->assertFieldChecked('edit-site-default-language-en', 'English is the default language.');
// Change the default language.
$edit = array(
$edit = [
'site_default_language' => 'fr',
);
];
$this->drupalPostForm(NULL, $edit, t('Save configuration'));
$this->rebuildContainer();
$this->assertFieldChecked('edit-site-default-language-fr', 'Default language updated.');
@ -80,16 +80,16 @@ class LanguageConfigurationTest extends WebTestBase {
$this->assertFieldByXPath('//input[@name="prefix[fr]"]', 'fr', 'French still has a path prefix.');
// Check that prefix can be changed.
$edit = array(
$edit = [
'prefix[fr]' => 'french',
);
];
$this->drupalPostForm(NULL, $edit, t('Save configuration'));
$this->assertFieldByXPath('//input[@name="prefix[fr]"]', 'french', 'French path prefix has changed.');
// Check that the prefix can be removed.
$edit = array(
$edit = [
'prefix[fr]' => '',
);
];
$this->drupalPostForm(NULL, $edit, t('Save configuration'));
$this->assertNoText(t('The prefix may only be left blank for the selected detection fallback language.'), 'The path prefix can be removed for the default language');
@ -97,24 +97,24 @@ class LanguageConfigurationTest extends WebTestBase {
$this->config('language.negotiation')->set('selected_langcode', 'fr')->save();
// Check that the prefix of a language that is not the negotiation one
// cannot be changed to empty string.
$edit = array(
$edit = [
'prefix[en]' => '',
);
];
$this->drupalPostForm(NULL, $edit, t('Save configuration'));
$this->assertText(t('The prefix may only be left blank for the selected detection fallback language.'));
// Check that prefix cannot be changed to contain a slash.
$edit = array(
$edit = [
'prefix[en]' => 'foo/bar',
);
];
$this->drupalPostForm(NULL, $edit, t('Save configuration'));
$this->assertText(t('The prefix may not contain a slash.'), 'English prefix cannot be changed to contain a slash.');
// Remove English language and add a new Language to check if langcode of
// Language entity is 'en'.
$this->drupalPostForm('admin/config/regional/language/delete/en', array(), t('Delete'));
$this->drupalPostForm('admin/config/regional/language/delete/en', [], t('Delete'));
$this->rebuildContainer();
$this->assertRaw(t('The %language (%langcode) language has been removed.', array('%language' => 'English', '%langcode' => 'en')));
$this->assertRaw(t('The %language (%langcode) language has been removed.', ['%language' => 'English', '%langcode' => 'en']));
// Ensure that French language has a weight of 1 after being created through
// the UI.
@ -132,9 +132,9 @@ class LanguageConfigurationTest extends WebTestBase {
$arabic->setWeight(4)->save();
$this->assertEqual($arabic->getWeight(), 4, 'The Arabic language has a weight of 0.');
$edit = array(
$edit = [
'predefined_langcode' => 'de',
);
];
$this->drupalPostForm('admin/config/regional/language/add', $edit, 'Add language');
$language = $this->config('language.entity.de')->get();
$this->assertEqual($language['langcode'], 'fr');
@ -148,30 +148,30 @@ class LanguageConfigurationTest extends WebTestBase {
/**
* Functional tests for setting system language weight on adding, editing and deleting languages.
*/
function testLanguageConfigurationWeight() {
public function testLanguageConfigurationWeight() {
// User to add and remove language.
$admin_user = $this->drupalCreateUser(array('administer languages', 'access administration pages'));
$admin_user = $this->drupalCreateUser(['administer languages', 'access administration pages']);
$this->drupalLogin($admin_user);
$this->checkConfigurableLanguageWeight();
// Add predefined language.
$edit = array(
$edit = [
'predefined_langcode' => 'fr',
);
];
$this->drupalPostForm('admin/config/regional/language/add', $edit, 'Add language');
$this->checkConfigurableLanguageWeight('after adding new language');
// Re-ordering languages.
$edit = array(
$edit = [
'languages[en][weight]' => $this->getHighestConfigurableLanguageWeight() + 1,
);
];
$this->drupalPostForm('admin/config/regional/language', $edit, 'Save configuration');
$this->checkConfigurableLanguageWeight('after re-ordering');
// Remove predefined language.
$edit = array(
$edit = [
'confirm' => 1,
);
];
$this->drupalPostForm('admin/config/regional/language/delete/fr', $edit, 'Delete');
$this->checkConfigurableLanguageWeight('after deleting a language');
}
@ -188,7 +188,7 @@ class LanguageConfigurationTest extends WebTestBase {
// Reset language list.
\Drupal::languageManager()->reset();
$max_configurable_language_weight = $this->getHighestConfigurableLanguageWeight();
$replacements = array('@event' => $state);
$replacements = ['@event' => $state];
foreach (\Drupal::languageManager()->getLanguages(LanguageInterface::STATE_LOCKED) as $locked_language) {
$replacements['%language'] = $locked_language->getName();
$this->assertTrue($locked_language->getWeight() > $max_configurable_language_weight, format_string('System language %language has higher weight than configurable languages @event', $replacements));

View file

@ -18,7 +18,7 @@ class LanguageCustomLanguageConfigurationTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('language');
public static $modules = ['language'];
/**
* Functional tests for adding, editing and deleting languages.
@ -26,76 +26,76 @@ class LanguageCustomLanguageConfigurationTest extends WebTestBase {
public function testLanguageConfiguration() {
// Create user with permissions to add and remove languages.
$admin_user = $this->drupalCreateUser(array('administer languages', 'access administration pages'));
$admin_user = $this->drupalCreateUser(['administer languages', 'access administration pages']);
$this->drupalLogin($admin_user);
// Add custom language.
$edit = array(
$edit = [
'predefined_langcode' => 'custom',
);
];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
// Test validation on missing values.
$this->assertText(t('@name field is required.', array('@name' => t('Language code'))));
$this->assertText(t('@name field is required.', array('@name' => t('Language name'))));
$this->assertText(t('@name field is required.', ['@name' => t('Language code')]));
$this->assertText(t('@name field is required.', ['@name' => t('Language name')]));
$empty_language = new Language();
$this->assertFieldChecked('edit-direction-' . $empty_language->getDirection(), 'Consistent usage of language direction.');
$this->assertUrl(\Drupal::url('language.add', array(), array('absolute' => TRUE)), [], 'Correct page redirection.');
$this->assertUrl(\Drupal::url('language.add', [], ['absolute' => TRUE]), [], 'Correct page redirection.');
// Test validation of invalid values.
$edit = array(
$edit = [
'predefined_langcode' => 'custom',
'langcode' => 'white space',
'label' => '<strong>evil markup</strong>',
'direction' => LanguageInterface::DIRECTION_LTR,
);
];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
$this->assertRaw(t('%field must be a valid language tag as <a href=":url">defined by the W3C</a>.', array(
$this->assertRaw(t('%field must be a valid language tag as <a href=":url">defined by the W3C</a>.', [
'%field' => t('Language code'),
':url' => 'http://www.w3.org/International/articles/language-tags/',
)));
]));
$this->assertRaw(t('%field cannot contain any markup.', array('%field' => t('Language name'))));
$this->assertUrl(\Drupal::url('language.add', array(), array('absolute' => TRUE)), [], 'Correct page redirection.');
$this->assertRaw(t('%field cannot contain any markup.', ['%field' => t('Language name')]));
$this->assertUrl(\Drupal::url('language.add', [], ['absolute' => TRUE]), [], 'Correct page redirection.');
// Test adding a custom language with a numeric region code.
$edit = array(
$edit = [
'predefined_langcode' => 'custom',
'langcode' => 'es-419',
'label' => 'Latin American Spanish',
'direction' => LanguageInterface::DIRECTION_LTR,
);
];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
$this->assertRaw(t(
'The language %language has been created and can now be used.',
array('%language' => $edit['label'])
['%language' => $edit['label']]
));
$this->assertUrl(\Drupal::url('entity.configurable_language.collection', array(), array('absolute' => TRUE)), [], 'Correct page redirection.');
$this->assertUrl(\Drupal::url('entity.configurable_language.collection', [], ['absolute' => TRUE]), [], 'Correct page redirection.');
// Test validation of existing language values.
$edit = array(
$edit = [
'predefined_langcode' => 'custom',
'langcode' => 'de',
'label' => 'German',
'direction' => LanguageInterface::DIRECTION_LTR,
);
];
// Add the language the first time.
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
$this->assertRaw(t(
'The language %language has been created and can now be used.',
array('%language' => $edit['label'])
['%language' => $edit['label']]
));
$this->assertUrl(\Drupal::url('entity.configurable_language.collection', array(), array('absolute' => TRUE)), [], 'Correct page redirection.');
$this->assertUrl(\Drupal::url('entity.configurable_language.collection', [], ['absolute' => TRUE]), [], 'Correct page redirection.');
// Add the language a second time and confirm that this is not allowed.
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
$this->assertRaw(t(
'The language %language (%langcode) already exists.',
array('%language' => $edit['label'], '%langcode' => $edit['langcode'])
['%language' => $edit['label'], '%langcode' => $edit['langcode']]
));
$this->assertUrl(\Drupal::url('language.add', array(), array('absolute' => TRUE)), [], 'Correct page redirection.');
$this->assertUrl(\Drupal::url('language.add', [], ['absolute' => TRUE]), [], 'Correct page redirection.');
}
}

View file

@ -19,15 +19,15 @@ class LanguageListTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('language');
public static $modules = ['language'];
/**
* Functional tests for adding, editing and deleting languages.
*/
function testLanguageList() {
public function testLanguageList() {
// User to add and remove language.
$admin_user = $this->drupalCreateUser(array('administer languages', 'access administration pages'));
$admin_user = $this->drupalCreateUser(['administer languages', 'access administration pages']);
$this->drupalLogin($admin_user);
// Get the weight of the last language.
@ -35,9 +35,9 @@ class LanguageListTest extends WebTestBase {
$last_language_weight = end($languages)->getWeight();
// Add predefined language.
$edit = array(
$edit = [
'predefined_langcode' => 'fr',
);
];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));
$this->assertText('French', 'Language added successfully.');
$this->assertUrl(\Drupal::url('entity.configurable_language.collection', [], ['absolute' => TRUE]));
@ -53,12 +53,12 @@ class LanguageListTest extends WebTestBase {
// Add custom language.
$langcode = 'xx';
$name = $this->randomMachineName(16);
$edit = array(
$edit = [
'predefined_langcode' => 'custom',
'langcode' => $langcode,
'label' => $name,
'direction' => Language::DIRECTION_LTR,
);
];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
$this->assertUrl(\Drupal::url('entity.configurable_language.collection', [], ['absolute' => TRUE]));
$this->assertRaw('"edit-languages-' . $langcode . '-weight"', 'Language code found.');
@ -72,9 +72,9 @@ class LanguageListTest extends WebTestBase {
$this->drupalGet($path);
$this->assertFieldChecked('edit-site-default-language-en', 'English is the default language.');
// Change the default language.
$edit = array(
$edit = [
'site_default_language' => $langcode,
);
];
$this->drupalPostForm(NULL, $edit, t('Save configuration'));
$this->rebuildContainer();
$this->assertNoFieldChecked('edit-site-default-language-en', 'Default language updated.');
@ -90,17 +90,17 @@ class LanguageListTest extends WebTestBase {
$this->assertTitle(t('Edit language | Drupal'), 'Page title is "Edit language".');
// Edit a language.
$name = $this->randomMachineName(16);
$edit = array(
$edit = [
'label' => $name,
);
];
$this->drupalPostForm('admin/config/regional/language/edit/' . $langcode, $edit, t('Save language'));
$this->assertRaw($name, 'The language has been updated.');
$this->assertUrl(\Drupal::url('entity.configurable_language.collection', [], ['absolute' => TRUE, 'language' => $language]));
// Change back the default language.
$edit = array(
$edit = [
'site_default_language' => 'en',
);
];
$this->drupalPostForm($path, $edit, t('Save configuration'));
$this->rebuildContainer();
// Ensure 'delete' link works.
@ -115,9 +115,9 @@ class LanguageListTest extends WebTestBase {
$this->assertRaw($name, 'The language was not deleted.');
// Delete the language for real. This a confirm form, we do not need any
// fields changed.
$this->drupalPostForm('admin/config/regional/language/delete/' . $langcode, array(), t('Delete'));
$this->drupalPostForm('admin/config/regional/language/delete/' . $langcode, [], t('Delete'));
// We need raw here because %language and %langcode will add HTML.
$t_args = array('%language' => $name, '%langcode' => $langcode);
$t_args = ['%language' => $name, '%langcode' => $langcode];
$this->assertRaw(t('The %language (%langcode) language has been removed.', $t_args), 'The test language has been removed.');
$this->assertUrl(\Drupal::url('entity.configurable_language.collection', [], ['absolute' => TRUE, 'language' => $english]));
// Verify that language is no longer found.
@ -125,11 +125,11 @@ class LanguageListTest extends WebTestBase {
$this->assertResponse(404, 'Language no longer found.');
// Delete French.
$this->drupalPostForm('admin/config/regional/language/delete/fr', array(), t('Delete'));
$this->drupalPostForm('admin/config/regional/language/delete/fr', [], t('Delete'));
// Make sure the "language_count" state has been updated correctly.
$this->rebuildContainer();
// We need raw here because %language and %langcode will add HTML.
$t_args = array('%language' => 'French', '%langcode' => 'fr');
$t_args = ['%language' => 'French', '%langcode' => 'fr'];
$this->assertRaw(t('The %language (%langcode) language has been removed.', $t_args), 'The French language has been removed.');
$this->assertUrl(\Drupal::url('entity.configurable_language.collection', [], ['absolute' => TRUE]));
// Verify that language is no longer found.
@ -142,12 +142,12 @@ class LanguageListTest extends WebTestBase {
// deleting English.
$langcode = 'xx';
$name = $this->randomMachineName(16);
$edit = array(
$edit = [
'predefined_langcode' => 'custom',
'langcode' => $langcode,
'label' => $name,
'direction' => Language::DIRECTION_LTR,
);
];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
$this->assertUrl(\Drupal::url('entity.configurable_language.collection', [], ['absolute' => TRUE]));
$this->assertText($name, 'Name found.');
@ -157,17 +157,17 @@ class LanguageListTest extends WebTestBase {
$this->drupalGet($path);
$this->assertFieldChecked('edit-site-default-language-en', 'English is the default language.');
// Change the default language.
$edit = array(
$edit = [
'site_default_language' => $langcode,
);
];
$this->drupalPostForm(NULL, $edit, t('Save configuration'));
$this->rebuildContainer();
$this->assertNoFieldChecked('edit-site-default-language-en', 'Default language updated.');
$this->assertUrl(\Drupal::url('entity.configurable_language.collection', [], ['absolute' => TRUE, 'language' => $language]));
$this->drupalPostForm('admin/config/regional/language/delete/en', array(), t('Delete'));
$this->drupalPostForm('admin/config/regional/language/delete/en', [], t('Delete'));
// We need raw here because %language and %langcode will add HTML.
$t_args = array('%language' => 'English', '%langcode' => 'en');
$t_args = ['%language' => 'English', '%langcode' => 'en'];
$this->assertRaw(t('The %language (%langcode) language has been removed.', $t_args), 'The English language has been removed.');
$this->rebuildContainer();
@ -178,7 +178,7 @@ class LanguageListTest extends WebTestBase {
// Ensure that NL cannot be set default when it's not available.
$this->drupalGet('admin/config/regional/language');
$extra_values = '&site_default_language=nl';
$this->drupalPostForm(NULL, array(), t('Save configuration'), array(), array(), NULL, $extra_values);
$this->drupalPostForm(NULL, [], t('Save configuration'), [], [], NULL, $extra_values);
$this->assertText(t('Selected default language no longer exists.'));
$this->assertNoFieldChecked('edit-site-default-language-xx', 'The previous default language got deselected.');
}
@ -186,24 +186,24 @@ class LanguageListTest extends WebTestBase {
/**
* Functional tests for the language states (locked or configurable).
*/
function testLanguageStates() {
public function testLanguageStates() {
// Add some languages, and also lock some of them.
ConfigurableLanguage::create(array('label' => $this->randomMachineName(), 'id' => 'l1'))->save();
ConfigurableLanguage::create(array('label' => $this->randomMachineName(), 'id' => 'l2', 'locked' => TRUE))->save();
ConfigurableLanguage::create(array('label' => $this->randomMachineName(), 'id' => 'l3'))->save();
ConfigurableLanguage::create(array('label' => $this->randomMachineName(), 'id' => 'l4', 'locked' => TRUE))->save();
$expected_locked_languages = array('l4' => 'l4', 'l2' => 'l2', 'und' => 'und', 'zxx' => 'zxx');
$expected_all_languages = array('l4' => 'l4', 'l3' => 'l3', 'l2' => 'l2', 'l1' => 'l1', 'en' => 'en', 'und' => 'und', 'zxx' => 'zxx');
$expected_conf_languages = array('l3' => 'l3', 'l1' => 'l1', 'en' => 'en');
ConfigurableLanguage::create(['label' => $this->randomMachineName(), 'id' => 'l1'])->save();
ConfigurableLanguage::create(['label' => $this->randomMachineName(), 'id' => 'l2', 'locked' => TRUE])->save();
ConfigurableLanguage::create(['label' => $this->randomMachineName(), 'id' => 'l3'])->save();
ConfigurableLanguage::create(['label' => $this->randomMachineName(), 'id' => 'l4', 'locked' => TRUE])->save();
$expected_locked_languages = ['l4' => 'l4', 'l2' => 'l2', 'und' => 'und', 'zxx' => 'zxx'];
$expected_all_languages = ['l4' => 'l4', 'l3' => 'l3', 'l2' => 'l2', 'l1' => 'l1', 'en' => 'en', 'und' => 'und', 'zxx' => 'zxx'];
$expected_conf_languages = ['l3' => 'l3', 'l1' => 'l1', 'en' => 'en'];
$locked_languages = $this->container->get('language_manager')->getLanguages(LanguageInterface::STATE_LOCKED);
$this->assertEqual(array_diff_key($expected_locked_languages, $locked_languages), array(), 'Locked languages loaded correctly.');
$this->assertEqual(array_diff_key($expected_locked_languages, $locked_languages), [], 'Locked languages loaded correctly.');
$all_languages = $this->container->get('language_manager')->getLanguages(LanguageInterface::STATE_ALL);
$this->assertEqual(array_diff_key($expected_all_languages, $all_languages), array(), 'All languages loaded correctly.');
$this->assertEqual(array_diff_key($expected_all_languages, $all_languages), [], 'All languages loaded correctly.');
$conf_languages = $this->container->get('language_manager')->getLanguages();
$this->assertEqual(array_diff_key($expected_conf_languages, $conf_languages), array(), 'Configurable languages loaded correctly.');
$this->assertEqual(array_diff_key($expected_conf_languages, $conf_languages), [], 'Configurable languages loaded correctly.');
}
}

View file

@ -16,7 +16,7 @@ class LanguageLocaleListTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('language', 'locale');
public static $modules = ['language', 'locale'];
/**
* {@inheritdoc}
@ -30,30 +30,30 @@ class LanguageLocaleListTest extends WebTestBase {
/**
* Tests adding, editing, and deleting languages.
*/
function testLanguageLocaleList() {
public function testLanguageLocaleList() {
// User to add and remove language.
$admin_user = $this->drupalCreateUser(array('administer languages', 'access administration pages'));
$admin_user = $this->drupalCreateUser(['administer languages', 'access administration pages']);
$this->drupalLogin($admin_user);
// Add predefined language.
$edit = array(
$edit = [
'predefined_langcode' => 'fr',
);
];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));
$this->assertText('The language French has been created and can now be used');
$this->assertUrl(\Drupal::url('entity.configurable_language.collection', [], ['absolute' => TRUE]));
$this->rebuildContainer();
// Translate Spanish language to French (Espagnol).
$source = $this->storage->createString(array(
$source = $this->storage->createString([
'source' => 'Spanish',
'context' => '',
))->save();
$this->storage->createTranslation(array(
])->save();
$this->storage->createTranslation([
'lid' => $source->lid,
'language' => 'fr',
'translation' => 'Espagnol',
))->save();
])->save();
// Get language list displayed in select list.
$this->drupalGet('fr/admin/config/regional/language/add');

View file

@ -16,7 +16,7 @@ class LanguageSelectorTranslatableTest extends WebTestBase {
*
* @var array
*/
public static $modules = array(
public static $modules = [
'language',
'content_translation',
'node',
@ -24,7 +24,7 @@ class LanguageSelectorTranslatableTest extends WebTestBase {
'field_ui',
'entity_test',
'locale',
);
];
/**
* The user with administrator privileges.
@ -49,13 +49,13 @@ class LanguageSelectorTranslatableTest extends WebTestBase {
*/
protected function getAdministratorPermissions() {
return array_filter(
array('translate interface',
['translate interface',
'administer content translation',
'create content translations',
'update content translations',
'delete content translations',
'administer languages',
)
]
);
}
@ -64,7 +64,7 @@ class LanguageSelectorTranslatableTest extends WebTestBase {
*/
public function testLanguageStringSelector() {
// Add another language.
$edit = array('predefined_langcode' => 'es');
$edit = ['predefined_langcode' => 'es'];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));
// Translate the string English in Spanish (Inglés). Override config entity.
@ -79,7 +79,7 @@ class LanguageSelectorTranslatableTest extends WebTestBase {
$this->drupalGet($path);
// Get en language from selector.
$elements = $this->xpath('//select[@id=:id]//option[@value=:option]', array(':id' => 'edit-settings-user-user-settings-language-langcode', ':option' => 'en'));
$elements = $this->xpath('//select[@id=:id]//option[@value=:option]', [':id' => 'edit-settings-user-user-settings-language-langcode', ':option' => 'en']);
// Check that the language text is translated.
$this->assertEqual((string) $elements[0], $name_translation, 'Checking the option string English is translated to Spanish.');

View file

@ -20,39 +20,39 @@ class LanguageSwitchingTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('locale', 'locale_test', 'language', 'block', 'language_test', 'menu_ui');
public static $modules = ['locale', 'locale_test', 'language', 'block', 'language_test', 'menu_ui'];
protected function setUp() {
parent::setUp();
// Create and log in user.
$admin_user = $this->drupalCreateUser(array('administer blocks', 'administer languages', 'access administration pages'));
$admin_user = $this->drupalCreateUser(['administer blocks', 'administer languages', 'access administration pages']);
$this->drupalLogin($admin_user);
}
/**
* Functional tests for the language switcher block.
*/
function testLanguageBlock() {
public function testLanguageBlock() {
// Add language.
$edit = array(
$edit = [
'predefined_langcode' => 'fr',
);
];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));
// Set the native language name.
$this->saveNativeLanguageName('fr', 'français');
// Enable URL language detection and selection.
$edit = array('language_interface[enabled][language-url]' => '1');
$edit = ['language_interface[enabled][language-url]' => '1'];
$this->drupalPostForm('admin/config/regional/language/detection', $edit, t('Save settings'));
// Enable the language switching block.
$block = $this->drupalPlaceBlock('language_block:' . LanguageInterface::TYPE_INTERFACE, array(
$block = $this->drupalPlaceBlock('language_block:' . LanguageInterface::TYPE_INTERFACE, [
'id' => 'test_language_block',
// Ensure a 2-byte UTF-8 sequence is in the tested output.
'label' => $this->randomMachineName(8) . '×',
));
]);
$this->doTestLanguageBlockAuthenticated($block->label());
$this->doTestLanguageBlockAnonymous($block->label());
@ -73,38 +73,38 @@ class LanguageSwitchingTest extends WebTestBase {
// Assert that each list item and anchor element has the appropriate data-
// attributes.
list($language_switcher) = $this->xpath('//div[@id=:id]', array(':id' => 'block-test-language-block'));
$list_items = array();
$anchors = array();
$labels = array();
list($language_switcher) = $this->xpath('//div[@id=:id]', [':id' => 'block-test-language-block']);
$list_items = [];
$anchors = [];
$labels = [];
foreach ($language_switcher->ul->li as $list_item) {
$classes = explode(" ", (string) $list_item['class']);
list($langcode) = array_intersect($classes, array('en', 'fr'));
$list_items[] = array(
list($langcode) = array_intersect($classes, ['en', 'fr']);
$list_items[] = [
'langcode_class' => $langcode,
'data-drupal-link-system-path' => (string) $list_item['data-drupal-link-system-path'],
);
$anchors[] = array(
];
$anchors[] = [
'hreflang' => (string) $list_item->a['hreflang'],
'data-drupal-link-system-path' => (string) $list_item->a['data-drupal-link-system-path'],
);
];
$labels[] = (string) $list_item->a;
}
$expected_list_items = array(
0 => array('langcode_class' => 'en', 'data-drupal-link-system-path' => 'user/2'),
1 => array('langcode_class' => 'fr', 'data-drupal-link-system-path' => 'user/2'),
);
$expected_list_items = [
0 => ['langcode_class' => 'en', 'data-drupal-link-system-path' => 'user/2'],
1 => ['langcode_class' => 'fr', 'data-drupal-link-system-path' => 'user/2'],
];
$this->assertIdentical($list_items, $expected_list_items, 'The list items have the correct attributes that will allow the drupal.active-link library to mark them as active.');
$expected_anchors = array(
0 => array('hreflang' => 'en', 'data-drupal-link-system-path' => 'user/2'),
1 => array('hreflang' => 'fr', 'data-drupal-link-system-path' => 'user/2'),
);
$expected_anchors = [
0 => ['hreflang' => 'en', 'data-drupal-link-system-path' => 'user/2'],
1 => ['hreflang' => 'fr', 'data-drupal-link-system-path' => 'user/2'],
];
$this->assertIdentical($anchors, $expected_anchors, 'The anchors have the correct attributes that will allow the drupal.active-link library to mark them as active.');
$settings = $this->getDrupalSettings();
$this->assertIdentical($settings['path']['currentPath'], 'user/2', 'drupalSettings.path.currentPath is set correctly to allow drupal.active-link to mark the correct links as active.');
$this->assertIdentical($settings['path']['isFront'], FALSE, 'drupalSettings.path.isFront is set correctly to allow drupal.active-link to mark the correct links as active.');
$this->assertIdentical($settings['path']['currentLanguage'], 'en', 'drupalSettings.path.currentLanguage is set correctly to allow drupal.active-link to mark the correct links as active.');
$this->assertIdentical($labels, array('English', 'français'), 'The language links labels are in their own language on the language switcher block.');
$this->assertIdentical($labels, ['English', 'français'], 'The language links labels are in their own language on the language switcher block.');
}
/**
@ -124,19 +124,19 @@ class LanguageSwitchingTest extends WebTestBase {
$this->assertText($block_label, 'Language switcher block found.');
// Assert that only the current language is marked as active.
list($language_switcher) = $this->xpath('//div[@id=:id]', array(':id' => 'block-test-language-block'));
$links = array(
'active' => array(),
'inactive' => array(),
);
$anchors = array(
'active' => array(),
'inactive' => array(),
);
$labels = array();
list($language_switcher) = $this->xpath('//div[@id=:id]', [':id' => 'block-test-language-block']);
$links = [
'active' => [],
'inactive' => [],
];
$anchors = [
'active' => [],
'inactive' => [],
];
$labels = [];
foreach ($language_switcher->ul->li as $link) {
$classes = explode(" ", (string) $link['class']);
list($langcode) = array_intersect($classes, array('en', 'fr'));
list($langcode) = array_intersect($classes, ['en', 'fr']);
if (in_array('is-active', $classes)) {
$links['active'][] = $langcode;
}
@ -152,15 +152,15 @@ class LanguageSwitchingTest extends WebTestBase {
}
$labels[] = (string) $link->a;
}
$this->assertIdentical($links, array('active' => array('en'), 'inactive' => array('fr')), 'Only the current language list item is marked as active on the language switcher block.');
$this->assertIdentical($anchors, array('active' => array('en'), 'inactive' => array('fr')), 'Only the current language anchor is marked as active on the language switcher block.');
$this->assertIdentical($labels, array('English', 'français'), 'The language links labels are in their own language on the language switcher block.');
$this->assertIdentical($links, ['active' => ['en'], 'inactive' => ['fr']], 'Only the current language list item is marked as active on the language switcher block.');
$this->assertIdentical($anchors, ['active' => ['en'], 'inactive' => ['fr']], 'Only the current language anchor is marked as active on the language switcher block.');
$this->assertIdentical($labels, ['English', 'français'], 'The language links labels are in their own language on the language switcher block.');
}
/**
* Test language switcher links for domain based negotiation.
*/
function testLanguageBlockWithDomain() {
public function testLanguageBlockWithDomain() {
// Add the Italian language.
ConfigurableLanguage::createFromLangcode('it')->save();
@ -171,31 +171,31 @@ class LanguageSwitchingTest extends WebTestBase {
$languages = $this->container->get('language_manager')->getLanguages();
// Enable browser and URL language detection.
$edit = array(
$edit = [
'language_interface[enabled][language-url]' => TRUE,
'language_interface[weight][language-url]' => -10,
);
];
$this->drupalPostForm('admin/config/regional/language/detection', $edit, t('Save settings'));
// Do not allow blank domain.
$edit = array(
$edit = [
'language_negotiation_url_part' => LanguageNegotiationUrl::CONFIG_DOMAIN,
'domain[en]' => '',
);
];
$this->drupalPostForm('admin/config/regional/language/detection/url', $edit, t('Save configuration'));
$this->assertText(t('The domain may not be left blank for English'), 'The form does not allow blank domains.');
// Change the domain for the Italian language.
$edit = array(
$edit = [
'language_negotiation_url_part' => LanguageNegotiationUrl::CONFIG_DOMAIN,
'domain[en]' => \Drupal::request()->getHost(),
'domain[it]' => 'it.example.com',
);
];
$this->drupalPostForm('admin/config/regional/language/detection/url', $edit, t('Save configuration'));
$this->assertText(t('The configuration options have been saved'), 'Domain configuration is saved.');
// Enable the language switcher block.
$this->drupalPlaceBlock('language_block:' . LanguageInterface::TYPE_INTERFACE, array('id' => 'test_language_block'));
$this->drupalPlaceBlock('language_block:' . LanguageInterface::TYPE_INTERFACE, ['id' => 'test_language_block']);
$this->drupalGet('');
@ -203,34 +203,34 @@ class LanguageSwitchingTest extends WebTestBase {
$generator = $this->container->get('url_generator');
// Verify the English URL is correct
list($english_link) = $this->xpath('//div[@id=:id]/ul/li/a[@hreflang=:hreflang]', array(
list($english_link) = $this->xpath('//div[@id=:id]/ul/li/a[@hreflang=:hreflang]', [
':id' => 'block-test-language-block',
':hreflang' => 'en',
));
$english_url = $generator->generateFromRoute('entity.user.canonical', array('user' => 2), array('language' => $languages['en']));
]);
$english_url = $generator->generateFromRoute('entity.user.canonical', ['user' => 2], ['language' => $languages['en']]);
$this->assertEqual($english_url, (string) $english_link['href']);
// Verify the Italian URL is correct
list($italian_link) = $this->xpath('//div[@id=:id]/ul/li/a[@hreflang=:hreflang]', array(
list($italian_link) = $this->xpath('//div[@id=:id]/ul/li/a[@hreflang=:hreflang]', [
':id' => 'block-test-language-block',
':hreflang' => 'it',
));
$italian_url = $generator->generateFromRoute('entity.user.canonical', array('user' => 2), array('language' => $languages['it']));
]);
$italian_url = $generator->generateFromRoute('entity.user.canonical', ['user' => 2], ['language' => $languages['it']]);
$this->assertEqual($italian_url, (string) $italian_link['href']);
}
/**
* Test active class on links when switching languages.
*/
function testLanguageLinkActiveClass() {
public function testLanguageLinkActiveClass() {
// Add language.
$edit = array(
$edit = [
'predefined_langcode' => 'fr',
);
];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));
// Enable URL language detection and selection.
$edit = array('language_interface[enabled][language-url]' => '1');
$edit = ['language_interface[enabled][language-url]' => '1'];
$this->drupalPostForm('admin/config/regional/language/detection', $edit, t('Save settings'));
$this->doTestLanguageLinkActiveClassAuthenticated();
@ -240,27 +240,27 @@ class LanguageSwitchingTest extends WebTestBase {
/**
* Check the path-admin class, as same as on default language.
*/
function testLanguageBodyClass() {
public function testLanguageBodyClass() {
$searched_class = 'path-admin';
// Add language.
$edit = array(
$edit = [
'predefined_langcode' => 'fr',
);
];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));
// Enable URL language detection and selection.
$edit = array('language_interface[enabled][language-url]' => '1');
$edit = ['language_interface[enabled][language-url]' => '1'];
$this->drupalPostForm('admin/config/regional/language/detection', $edit, t('Save settings'));
// Check if the default (English) admin/config page has the right class.
$this->drupalGet('admin/config');
$class = $this->xpath('//body[contains(@class, :class)]', array(':class' => $searched_class));
$class = $this->xpath('//body[contains(@class, :class)]', [':class' => $searched_class]);
$this->assertTrue(isset($class[0]), t('The path-admin class appears on default language.'));
// Check if the French admin/config page has the right class.
$this->drupalGet('fr/admin/config');
$class = $this->xpath('//body[contains(@class, :class)]', array(':class' => $searched_class));
$class = $this->xpath('//body[contains(@class, :class)]', [':class' => $searched_class]);
$this->assertTrue(isset($class[0]), t('The path-admin class same as on default language.'));
// The testing profile sets the user/login page as the frontpage. That
@ -270,12 +270,12 @@ class LanguageSwitchingTest extends WebTestBase {
// Check if the default (English) frontpage has the right class.
$this->drupalGet('<front>');
$class = $this->xpath('//body[contains(@class, :class)]', array(':class' => 'path-frontpage'));
$class = $this->xpath('//body[contains(@class, :class)]', [':class' => 'path-frontpage']);
$this->assertTrue(isset($class[0]), 'path-frontpage class found on the body tag');
// Check if the French frontpage has the right class.
$this->drupalGet('fr');
$class = $this->xpath('//body[contains(@class, :class)]', array(':class' => 'path-frontpage'));
$class = $this->xpath('//body[contains(@class, :class)]', [':class' => 'path-frontpage']);
$this->assertTrue(isset($class[0]), 'path-frontpage class found on the body tag with french as the active language');
}
@ -295,18 +295,18 @@ class LanguageSwitchingTest extends WebTestBase {
// Language code 'none' link should be active.
$langcode = 'none';
$links = $this->xpath('//a[@id = :id and @data-drupal-link-system-path = :path]', array(':id' => 'no_lang_link', ':path' => $path));
$this->assertTrue(isset($links[0]), t('A link generated by :function to the current :language page with langcode :langcode has the correct attributes that will allow the drupal.active-link library to mark it as active.', array(':function' => $function_name, ':language' => $current_language, ':langcode' => $langcode)));
$links = $this->xpath('//a[@id = :id and @data-drupal-link-system-path = :path]', [':id' => 'no_lang_link', ':path' => $path]);
$this->assertTrue(isset($links[0]), t('A link generated by :function to the current :language page with langcode :langcode has the correct attributes that will allow the drupal.active-link library to mark it as active.', [':function' => $function_name, ':language' => $current_language, ':langcode' => $langcode]));
// Language code 'en' link should be active.
$langcode = 'en';
$links = $this->xpath('//a[@id = :id and @hreflang = :lang and @data-drupal-link-system-path = :path]', array(':id' => 'en_link', ':lang' => 'en', ':path' => $path));
$this->assertTrue(isset($links[0]), t('A link generated by :function to the current :language page with langcode :langcode has the correct attributes that will allow the drupal.active-link library to mark it as active.', array(':function' => $function_name, ':language' => $current_language, ':langcode' => $langcode)));
$links = $this->xpath('//a[@id = :id and @hreflang = :lang and @data-drupal-link-system-path = :path]', [':id' => 'en_link', ':lang' => 'en', ':path' => $path]);
$this->assertTrue(isset($links[0]), t('A link generated by :function to the current :language page with langcode :langcode has the correct attributes that will allow the drupal.active-link library to mark it as active.', [':function' => $function_name, ':language' => $current_language, ':langcode' => $langcode]));
// Language code 'fr' link should not be active.
$langcode = 'fr';
$links = $this->xpath('//a[@id = :id and @hreflang = :lang and @data-drupal-link-system-path = :path]', array(':id' => 'fr_link', ':lang' => 'fr', ':path' => $path));
$this->assertTrue(isset($links[0]), t('A link generated by :function to the current :language page with langcode :langcode has the correct attributes that will allow the drupal.active-link library to NOT mark it as active.', array(':function' => $function_name, ':language' => $current_language, ':langcode' => $langcode)));
$links = $this->xpath('//a[@id = :id and @hreflang = :lang and @data-drupal-link-system-path = :path]', [':id' => 'fr_link', ':lang' => 'fr', ':path' => $path]);
$this->assertTrue(isset($links[0]), t('A link generated by :function to the current :language page with langcode :langcode has the correct attributes that will allow the drupal.active-link library to NOT mark it as active.', [':function' => $function_name, ':language' => $current_language, ':langcode' => $langcode]));
// Verify that drupalSettings contains the correct values.
$settings = $this->getDrupalSettings();
@ -320,18 +320,18 @@ class LanguageSwitchingTest extends WebTestBase {
// Language code 'none' link should be active.
$langcode = 'none';
$links = $this->xpath('//a[@id = :id and @data-drupal-link-system-path = :path]', array(':id' => 'no_lang_link', ':path' => $path));
$this->assertTrue(isset($links[0]), t('A link generated by :function to the current :language page with langcode :langcode has the correct attributes that will allow the drupal.active-link library to mark it as active.', array(':function' => $function_name, ':language' => $current_language, ':langcode' => $langcode)));
$links = $this->xpath('//a[@id = :id and @data-drupal-link-system-path = :path]', [':id' => 'no_lang_link', ':path' => $path]);
$this->assertTrue(isset($links[0]), t('A link generated by :function to the current :language page with langcode :langcode has the correct attributes that will allow the drupal.active-link library to mark it as active.', [':function' => $function_name, ':language' => $current_language, ':langcode' => $langcode]));
// Language code 'en' link should not be active.
$langcode = 'en';
$links = $this->xpath('//a[@id = :id and @hreflang = :lang and @data-drupal-link-system-path = :path]', array(':id' => 'en_link', ':lang' => 'en', ':path' => $path));
$this->assertTrue(isset($links[0]), t('A link generated by :function to the current :language page with langcode :langcode has the correct attributes that will allow the drupal.active-link library to NOT mark it as active.', array(':function' => $function_name, ':language' => $current_language, ':langcode' => $langcode)));
$links = $this->xpath('//a[@id = :id and @hreflang = :lang and @data-drupal-link-system-path = :path]', [':id' => 'en_link', ':lang' => 'en', ':path' => $path]);
$this->assertTrue(isset($links[0]), t('A link generated by :function to the current :language page with langcode :langcode has the correct attributes that will allow the drupal.active-link library to NOT mark it as active.', [':function' => $function_name, ':language' => $current_language, ':langcode' => $langcode]));
// Language code 'fr' link should be active.
$langcode = 'fr';
$links = $this->xpath('//a[@id = :id and @hreflang = :lang and @data-drupal-link-system-path = :path]', array(':id' => 'fr_link', ':lang' => 'fr', ':path' => $path));
$this->assertTrue(isset($links[0]), t('A link generated by :function to the current :language page with langcode :langcode has the correct attributes that will allow the drupal.active-link library to mark it as active.', array(':function' => $function_name, ':language' => $current_language, ':langcode' => $langcode)));
$links = $this->xpath('//a[@id = :id and @hreflang = :lang and @data-drupal-link-system-path = :path]', [':id' => 'fr_link', ':lang' => 'fr', ':path' => $path]);
$this->assertTrue(isset($links[0]), t('A link generated by :function to the current :language page with langcode :langcode has the correct attributes that will allow the drupal.active-link library to mark it as active.', [':function' => $function_name, ':language' => $current_language, ':langcode' => $langcode]));
// Verify that drupalSettings contains the correct values.
$settings = $this->getDrupalSettings();
@ -356,18 +356,18 @@ class LanguageSwitchingTest extends WebTestBase {
// Language code 'none' link should be active.
$langcode = 'none';
$links = $this->xpath('//a[@id = :id and contains(@class, :class)]', array(':id' => 'no_lang_link', ':class' => 'is-active'));
$this->assertTrue(isset($links[0]), t('A link generated by :function to the current :language page with langcode :langcode is marked active.', array(':function' => $function_name, ':language' => $current_language, ':langcode' => $langcode)));
$links = $this->xpath('//a[@id = :id and contains(@class, :class)]', [':id' => 'no_lang_link', ':class' => 'is-active']);
$this->assertTrue(isset($links[0]), t('A link generated by :function to the current :language page with langcode :langcode is marked active.', [':function' => $function_name, ':language' => $current_language, ':langcode' => $langcode]));
// Language code 'en' link should be active.
$langcode = 'en';
$links = $this->xpath('//a[@id = :id and contains(@class, :class)]', array(':id' => 'en_link', ':class' => 'is-active'));
$this->assertTrue(isset($links[0]), t('A link generated by :function to the current :language page with langcode :langcode is marked active.', array(':function' => $function_name, ':language' => $current_language, ':langcode' => $langcode)));
$links = $this->xpath('//a[@id = :id and contains(@class, :class)]', [':id' => 'en_link', ':class' => 'is-active']);
$this->assertTrue(isset($links[0]), t('A link generated by :function to the current :language page with langcode :langcode is marked active.', [':function' => $function_name, ':language' => $current_language, ':langcode' => $langcode]));
// Language code 'fr' link should not be active.
$langcode = 'fr';
$links = $this->xpath('//a[@id = :id and not(contains(@class, :class))]', array(':id' => 'fr_link', ':class' => 'is-active'));
$this->assertTrue(isset($links[0]), t('A link generated by :function to the current :language page with langcode :langcode is NOT marked active.', array(':function' => $function_name, ':language' => $current_language, ':langcode' => $langcode)));
$links = $this->xpath('//a[@id = :id and not(contains(@class, :class))]', [':id' => 'fr_link', ':class' => 'is-active']);
$this->assertTrue(isset($links[0]), t('A link generated by :function to the current :language page with langcode :langcode is NOT marked active.', [':function' => $function_name, ':language' => $current_language, ':langcode' => $langcode]));
// Test links generated by the link generator on a French page.
$current_language = 'French';
@ -375,18 +375,18 @@ class LanguageSwitchingTest extends WebTestBase {
// Language code 'none' link should be active.
$langcode = 'none';
$links = $this->xpath('//a[@id = :id and contains(@class, :class)]', array(':id' => 'no_lang_link', ':class' => 'is-active'));
$this->assertTrue(isset($links[0]), t('A link generated by :function to the current :language page with langcode :langcode is marked active.', array(':function' => $function_name, ':language' => $current_language, ':langcode' => $langcode)));
$links = $this->xpath('//a[@id = :id and contains(@class, :class)]', [':id' => 'no_lang_link', ':class' => 'is-active']);
$this->assertTrue(isset($links[0]), t('A link generated by :function to the current :language page with langcode :langcode is marked active.', [':function' => $function_name, ':language' => $current_language, ':langcode' => $langcode]));
// Language code 'en' link should not be active.
$langcode = 'en';
$links = $this->xpath('//a[@id = :id and not(contains(@class, :class))]', array(':id' => 'en_link', ':class' => 'is-active'));
$this->assertTrue(isset($links[0]), t('A link generated by :function to the current :language page with langcode :langcode is NOT marked active.', array(':function' => $function_name, ':language' => $current_language, ':langcode' => $langcode)));
$links = $this->xpath('//a[@id = :id and not(contains(@class, :class))]', [':id' => 'en_link', ':class' => 'is-active']);
$this->assertTrue(isset($links[0]), t('A link generated by :function to the current :language page with langcode :langcode is NOT marked active.', [':function' => $function_name, ':language' => $current_language, ':langcode' => $langcode]));
// Language code 'fr' link should be active.
$langcode = 'fr';
$links = $this->xpath('//a[@id = :id and contains(@class, :class)]', array(':id' => 'fr_link', ':class' => 'is-active'));
$this->assertTrue(isset($links[0]), t('A link generated by :function to the current :language page with langcode :langcode is marked active.', array(':function' => $function_name, ':language' => $current_language, ':langcode' => $langcode)));
$links = $this->xpath('//a[@id = :id and contains(@class, :class)]', [':id' => 'fr_link', ':class' => 'is-active']);
$this->assertTrue(isset($links[0]), t('A link generated by :function to the current :language page with langcode :langcode is marked active.', [':function' => $function_name, ':language' => $current_language, ':langcode' => $langcode]));
}
/**
@ -394,27 +394,27 @@ class LanguageSwitchingTest extends WebTestBase {
*/
public function testLanguageSessionSwitchLinks() {
// Add language.
$edit = array(
$edit = [
'predefined_langcode' => 'fr',
);
];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));
// Enable session language detection and selection.
$edit = array(
$edit = [
'language_interface[enabled][language-url]' => FALSE,
'language_interface[enabled][language-session]' => TRUE,
);
];
$this->drupalPostForm('admin/config/regional/language/detection', $edit, t('Save settings'));
// Enable the language switching block.
$this->drupalPlaceBlock('language_block:' . LanguageInterface::TYPE_INTERFACE, array(
$this->drupalPlaceBlock('language_block:' . LanguageInterface::TYPE_INTERFACE, [
'id' => 'test_language_block',
));
]);
// Enable the main menu block.
$this->drupalPlaceBlock('system_menu_block:main', array(
$this->drupalPlaceBlock('system_menu_block:main', [
'id' => 'test_menu',
));
]);
// Add a link to the homepage.
$link = MenuLinkContent::create([

View file

@ -30,7 +30,7 @@ class LanguageTourTest extends TourTestBase {
*/
protected function setUp() {
parent::setUp();
$this->adminUser = $this->drupalCreateUser(array('administer languages', 'access tour'));
$this->adminUser = $this->drupalCreateUser(['administer languages', 'access tour']);
$this->drupalLogin($this->adminUser);
$this->drupalPlaceBlock('local_actions_block');
}

View file

@ -48,19 +48,19 @@ class LanguageUILanguageNegotiationTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('locale', 'language_test', 'block', 'user', 'content_translation');
public static $modules = ['locale', 'language_test', 'block', 'user', 'content_translation'];
protected function setUp() {
parent::setUp();
$admin_user = $this->drupalCreateUser(array('administer languages', 'translate interface', 'access administration pages', 'administer blocks'));
$admin_user = $this->drupalCreateUser(['administer languages', 'translate interface', 'access administration pages', 'administer blocks']);
$this->drupalLogin($admin_user);
}
/**
* Tests for language switching by URL path.
*/
function testUILanguageNegotiation() {
public function testUILanguageNegotiation() {
// A few languages to switch to.
// This one is unknown, should get the default lang version.
$langcode_unknown = 'blah-blah';
@ -69,9 +69,9 @@ class LanguageUILanguageNegotiationTest extends WebTestBase {
// For testing path prefix.
$langcode = 'zh-hans';
// For setting browser language preference to 'vi'.
$http_header_browser_fallback = array("Accept-Language: $langcode_browser_fallback;q=1");
$http_header_browser_fallback = ["Accept-Language: $langcode_browser_fallback;q=1"];
// For setting browser language preference to some unknown.
$http_header_blah = array("Accept-Language: blah;q=1");
$http_header_blah = ["Accept-Language: blah;q=1"];
// Setup the site languages by installing two languages.
// Set the default language in order for the translated string to be registered
@ -101,117 +101,117 @@ class LanguageUILanguageNegotiationTest extends WebTestBase {
$language_browser_fallback_string = "In $langcode_browser_fallback In $langcode_browser_fallback In $langcode_browser_fallback";
$language_string = "In $langcode In $langcode In $langcode";
// Do a translate search of our target string.
$search = array(
$search = [
'string' => $default_string,
'langcode' => $langcode_browser_fallback,
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$textarea = current($this->xpath('//textarea'));
$lid = (string) $textarea[0]['name'];
$edit = array(
$edit = [
$lid => $language_browser_fallback_string,
);
];
$this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));
$search = array(
$search = [
'string' => $default_string,
'langcode' => $langcode,
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$textarea = current($this->xpath('//textarea'));
$lid = (string) $textarea[0]['name'];
$edit = array(
$edit = [
$lid => $language_string,
);
];
$this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));
// Configure selected language negotiation to use zh-hans.
$edit = array('selected_langcode' => $langcode);
$edit = ['selected_langcode' => $langcode];
$this->drupalPostForm('admin/config/regional/language/detection/selected', $edit, t('Save configuration'));
$test = array(
'language_negotiation' => array(LanguageNegotiationSelected::METHOD_ID),
$test = [
'language_negotiation' => [LanguageNegotiationSelected::METHOD_ID],
'path' => 'admin/config',
'expect' => $language_string,
'expected_method_id' => LanguageNegotiationSelected::METHOD_ID,
'http_header' => $http_header_browser_fallback,
'message' => 'SELECTED: UI language is switched based on selected language.',
);
$this->runTest($test);
];
$this->doRunTest($test);
// An invalid language is selected.
$this->config('language.negotiation')->set('selected_langcode', NULL)->save();
$test = array(
'language_negotiation' => array(LanguageNegotiationSelected::METHOD_ID),
$test = [
'language_negotiation' => [LanguageNegotiationSelected::METHOD_ID],
'path' => 'admin/config',
'expect' => $default_string,
'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
'http_header' => $http_header_browser_fallback,
'message' => 'SELECTED > DEFAULT: UI language is switched based on selected language.',
);
$this->runTest($test);
];
$this->doRunTest($test);
// No selected language is available.
$this->config('language.negotiation')->set('selected_langcode', $langcode_unknown)->save();
$test = array(
'language_negotiation' => array(LanguageNegotiationSelected::METHOD_ID),
$test = [
'language_negotiation' => [LanguageNegotiationSelected::METHOD_ID],
'path' => 'admin/config',
'expect' => $default_string,
'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
'http_header' => $http_header_browser_fallback,
'message' => 'SELECTED > DEFAULT: UI language is switched based on selected language.',
);
$this->runTest($test);
];
$this->doRunTest($test);
$tests = array(
$tests = [
// Default, browser preference should have no influence.
array(
'language_negotiation' => array(LanguageNegotiationUrl::METHOD_ID, LanguageNegotiationSelected::METHOD_ID),
[
'language_negotiation' => [LanguageNegotiationUrl::METHOD_ID, LanguageNegotiationSelected::METHOD_ID],
'path' => 'admin/config',
'expect' => $default_string,
'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
'http_header' => $http_header_browser_fallback,
'message' => 'URL (PATH) > DEFAULT: no language prefix, UI language is default and the browser language preference setting is not used.',
),
],
// Language prefix.
array(
'language_negotiation' => array(LanguageNegotiationUrl::METHOD_ID, LanguageNegotiationSelected::METHOD_ID),
[
'language_negotiation' => [LanguageNegotiationUrl::METHOD_ID, LanguageNegotiationSelected::METHOD_ID],
'path' => "$langcode/admin/config",
'expect' => $language_string,
'expected_method_id' => LanguageNegotiationUrl::METHOD_ID,
'http_header' => $http_header_browser_fallback,
'message' => 'URL (PATH) > DEFAULT: with language prefix, UI language is switched based on path prefix',
),
],
// Default, go by browser preference.
array(
'language_negotiation' => array(LanguageNegotiationUrl::METHOD_ID, LanguageNegotiationBrowser::METHOD_ID),
[
'language_negotiation' => [LanguageNegotiationUrl::METHOD_ID, LanguageNegotiationBrowser::METHOD_ID],
'path' => 'admin/config',
'expect' => $language_browser_fallback_string,
'expected_method_id' => LanguageNegotiationBrowser::METHOD_ID,
'http_header' => $http_header_browser_fallback,
'message' => 'URL (PATH) > BROWSER: no language prefix, UI language is determined by browser language preference',
),
],
// Prefix, switch to the language.
array(
'language_negotiation' => array(LanguageNegotiationUrl::METHOD_ID, LanguageNegotiationBrowser::METHOD_ID),
[
'language_negotiation' => [LanguageNegotiationUrl::METHOD_ID, LanguageNegotiationBrowser::METHOD_ID],
'path' => "$langcode/admin/config",
'expect' => $language_string,
'expected_method_id' => LanguageNegotiationUrl::METHOD_ID,
'http_header' => $http_header_browser_fallback,
'message' => 'URL (PATH) > BROWSER: with language prefix, UI language is based on path prefix',
),
],
// Default, browser language preference is not one of site's lang.
array(
'language_negotiation' => array(LanguageNegotiationUrl::METHOD_ID, LanguageNegotiationBrowser::METHOD_ID, LanguageNegotiationSelected::METHOD_ID),
[
'language_negotiation' => [LanguageNegotiationUrl::METHOD_ID, LanguageNegotiationBrowser::METHOD_ID, LanguageNegotiationSelected::METHOD_ID],
'path' => 'admin/config',
'expect' => $default_string,
'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
'http_header' => $http_header_blah,
'message' => 'URL (PATH) > BROWSER > DEFAULT: no language prefix and browser language preference set to unknown language should use default language',
),
);
],
];
foreach ($tests as $test) {
$this->runTest($test);
$this->doRunTest($test);
}
// Unknown language prefix should return 404.
@ -224,7 +224,7 @@ class LanguageUILanguageNegotiationTest extends WebTestBase {
$this->config('language.types')
->set('negotiation.' . LanguageInterface::TYPE_INTERFACE . '.enabled', array_flip(array_keys($language_interface_method_definitions)))
->save();
$this->drupalGet("$langcode_unknown/admin/config", array(), $http_header_browser_fallback);
$this->drupalGet("$langcode_unknown/admin/config", [], $http_header_browser_fallback);
$this->assertResponse(404, "Unknown language path prefix should return 404");
// Set preferred langcode for user to NULL.
@ -232,117 +232,117 @@ class LanguageUILanguageNegotiationTest extends WebTestBase {
$account->preferred_langcode = NULL;
$account->save();
$test = array(
'language_negotiation' => array(LanguageNegotiationUser::METHOD_ID, LanguageNegotiationSelected::METHOD_ID),
$test = [
'language_negotiation' => [LanguageNegotiationUser::METHOD_ID, LanguageNegotiationSelected::METHOD_ID],
'path' => 'admin/config',
'expect' => $default_string,
'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
'http_header' => array(),
'http_header' => [],
'message' => 'USER > DEFAULT: no preferred user language setting, the UI language is default',
);
$this->runTest($test);
];
$this->doRunTest($test);
// Set preferred langcode for user to unknown language.
$account = $this->loggedInUser;
$account->preferred_langcode = $langcode_unknown;
$account->save();
$test = array(
'language_negotiation' => array(LanguageNegotiationUser::METHOD_ID, LanguageNegotiationSelected::METHOD_ID),
$test = [
'language_negotiation' => [LanguageNegotiationUser::METHOD_ID, LanguageNegotiationSelected::METHOD_ID],
'path' => 'admin/config',
'expect' => $default_string,
'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
'http_header' => array(),
'http_header' => [],
'message' => 'USER > DEFAULT: invalid preferred user language setting, the UI language is default',
);
$this->runTest($test);
];
$this->doRunTest($test);
// Set preferred langcode for user to non default.
$account->preferred_langcode = $langcode;
$account->save();
$test = array(
'language_negotiation' => array(LanguageNegotiationUser::METHOD_ID, LanguageNegotiationSelected::METHOD_ID),
$test = [
'language_negotiation' => [LanguageNegotiationUser::METHOD_ID, LanguageNegotiationSelected::METHOD_ID],
'path' => 'admin/config',
'expect' => $language_string,
'expected_method_id' => LanguageNegotiationUser::METHOD_ID,
'http_header' => array(),
'http_header' => [],
'message' => 'USER > DEFAULT: defined preferred user language setting, the UI language is based on user setting',
);
$this->runTest($test);
];
$this->doRunTest($test);
// Set preferred admin langcode for user to NULL.
$account->preferred_admin_langcode = NULL;
$account->save();
$test = array(
'language_negotiation' => array(LanguageNegotiationUserAdmin::METHOD_ID, LanguageNegotiationSelected::METHOD_ID),
$test = [
'language_negotiation' => [LanguageNegotiationUserAdmin::METHOD_ID, LanguageNegotiationSelected::METHOD_ID],
'path' => 'admin/config',
'expect' => $default_string,
'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
'http_header' => array(),
'http_header' => [],
'message' => 'USER ADMIN > DEFAULT: no preferred user admin language setting, the UI language is default',
);
$this->runTest($test);
];
$this->doRunTest($test);
// Set preferred admin langcode for user to unknown language.
$account->preferred_admin_langcode = $langcode_unknown;
$account->save();
$test = array(
'language_negotiation' => array(LanguageNegotiationUserAdmin::METHOD_ID, LanguageNegotiationSelected::METHOD_ID),
$test = [
'language_negotiation' => [LanguageNegotiationUserAdmin::METHOD_ID, LanguageNegotiationSelected::METHOD_ID],
'path' => 'admin/config',
'expect' => $default_string,
'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
'http_header' => array(),
'http_header' => [],
'message' => 'USER ADMIN > DEFAULT: invalid preferred user admin language setting, the UI language is default',
);
$this->runTest($test);
];
$this->doRunTest($test);
// Set preferred admin langcode for user to non default.
$account->preferred_admin_langcode = $langcode;
$account->save();
$test = array(
'language_negotiation' => array(LanguageNegotiationUserAdmin::METHOD_ID, LanguageNegotiationSelected::METHOD_ID),
$test = [
'language_negotiation' => [LanguageNegotiationUserAdmin::METHOD_ID, LanguageNegotiationSelected::METHOD_ID],
'path' => 'admin/config',
'expect' => $language_string,
'expected_method_id' => LanguageNegotiationUserAdmin::METHOD_ID,
'http_header' => array(),
'http_header' => [],
'message' => 'USER ADMIN > DEFAULT: defined preferred user admin language setting, the UI language is based on user setting',
);
$this->runTest($test);
];
$this->doRunTest($test);
// Go by session preference.
$language_negotiation_session_param = $this->randomMachineName();
$edit = array('language_negotiation_session_param' => $language_negotiation_session_param);
$edit = ['language_negotiation_session_param' => $language_negotiation_session_param];
$this->drupalPostForm('admin/config/regional/language/detection/session', $edit, t('Save configuration'));
$tests = array(
array(
'language_negotiation' => array(LanguageNegotiationSession::METHOD_ID),
$tests = [
[
'language_negotiation' => [LanguageNegotiationSession::METHOD_ID],
'path' => "admin/config",
'expect' => $default_string,
'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
'http_header' => $http_header_browser_fallback,
'message' => 'SESSION > DEFAULT: no language given, the UI language is default',
),
array(
'language_negotiation' => array(LanguageNegotiationSession::METHOD_ID),
],
[
'language_negotiation' => [LanguageNegotiationSession::METHOD_ID],
'path' => 'admin/config',
'path_options' => ['query' => [$language_negotiation_session_param => $langcode]],
'expect' => $language_string,
'expected_method_id' => LanguageNegotiationSession::METHOD_ID,
'http_header' => $http_header_browser_fallback,
'message' => 'SESSION > DEFAULT: language given, UI language is determined by session language preference',
),
);
],
];
foreach ($tests as $test) {
$this->runTest($test);
$this->doRunTest($test);
}
}
protected function runTest($test) {
$test += array('path_options' => []);
protected function doRunTest($test) {
$test += ['path_options' => []];
if (!empty($test['language_negotiation'])) {
$method_weights = array_flip($test['language_negotiation']);
$this->container->get('language_negotiator')->saveConfiguration(LanguageInterface::TYPE_INTERFACE, $method_weights);
@ -358,13 +358,13 @@ class LanguageUILanguageNegotiationTest extends WebTestBase {
$this->container->get('language_manager')->reset();
$this->drupalGet($test['path'], $test['path_options'], $test['http_header']);
$this->assertText($test['expect'], $test['message']);
$this->assertText(t('Language negotiation method: @name', array('@name' => $test['expected_method_id'])));
$this->assertText(t('Language negotiation method: @name', ['@name' => $test['expected_method_id']]));
}
/**
* Test URL language detection when the requested URL has no language.
*/
function testUrlLanguageFallback() {
public function testUrlLanguageFallback() {
// Add the Italian language.
$langcode_browser_fallback = 'it';
ConfigurableLanguage::createFromLangcode($langcode_browser_fallback)->save();
@ -372,21 +372,21 @@ class LanguageUILanguageNegotiationTest extends WebTestBase {
// Enable the path prefix for the default language: this way any unprefixed
// URL must have a valid fallback value.
$edit = array('prefix[en]' => 'en');
$edit = ['prefix[en]' => 'en'];
$this->drupalPostForm('admin/config/regional/language/detection/url', $edit, t('Save configuration'));
// Enable browser and URL language detection.
$edit = array(
$edit = [
'language_interface[enabled][language-browser]' => TRUE,
'language_interface[enabled][language-url]' => TRUE,
'language_interface[weight][language-browser]' => -8,
'language_interface[weight][language-url]' => -10,
);
];
$this->drupalPostForm('admin/config/regional/language/detection', $edit, t('Save settings'));
$this->drupalGet('admin/config/regional/language/detection');
// Enable the language switcher block.
$this->drupalPlaceBlock('language_block:' . LanguageInterface::TYPE_INTERFACE, array('id' => 'test_language_block'));
$this->drupalPlaceBlock('language_block:' . LanguageInterface::TYPE_INTERFACE, ['id' => 'test_language_block']);
// Log out, because for anonymous users, the "active" class is set by PHP
// (which means we can easily test it here), whereas for authenticated users
@ -398,13 +398,13 @@ class LanguageUILanguageNegotiationTest extends WebTestBase {
// Access the front page without specifying any valid URL language prefix
// and having as browser language preference a non-default language.
$http_header = array("Accept-Language: $langcode_browser_fallback;q=1");
$language = new Language(array('id' => ''));
$this->drupalGet('', array('language' => $language), $http_header);
$http_header = ["Accept-Language: $langcode_browser_fallback;q=1"];
$language = new Language(['id' => '']);
$this->drupalGet('', ['language' => $language], $http_header);
// Check that the language switcher active link matches the given browser
// language.
$args = array(':id' => 'block-test-language-block', ':url' => \Drupal::url('<front>') . $langcode_browser_fallback);
$args = [':id' => 'block-test-language-block', ':url' => \Drupal::url('<front>') . $langcode_browser_fallback];
$fields = $this->xpath('//div[@id=:id]//a[@class="language-link is-active" and starts-with(@href, :url)]', $args);
$this->assertTrue($fields[0] == $languages[$langcode_browser_fallback]->getName(), 'The browser language is the URL active language');
@ -416,7 +416,7 @@ class LanguageUILanguageNegotiationTest extends WebTestBase {
/**
* Tests URL handling when separate domains are used for multiple languages.
*/
function testLanguageDomain() {
public function testLanguageDomain() {
global $base_url;
// Get the current host URI we're running on.
@ -428,27 +428,27 @@ class LanguageUILanguageNegotiationTest extends WebTestBase {
$languages = $this->container->get('language_manager')->getLanguages();
// Enable browser and URL language detection.
$edit = array(
$edit = [
'language_interface[enabled][language-url]' => TRUE,
'language_interface[weight][language-url]' => -10,
);
];
$this->drupalPostForm('admin/config/regional/language/detection', $edit, t('Save settings'));
// Do not allow blank domain.
$edit = array(
$edit = [
'language_negotiation_url_part' => LanguageNegotiationUrl::CONFIG_DOMAIN,
'domain[en]' => '',
);
];
$this->drupalPostForm('admin/config/regional/language/detection/url', $edit, t('Save configuration'));
$this->assertText('The domain may not be left blank for English', 'The form does not allow blank domains.');
$this->rebuildContainer();
// Change the domain for the Italian language.
$edit = array(
$edit = [
'language_negotiation_url_part' => LanguageNegotiationUrl::CONFIG_DOMAIN,
'domain[en]' => $base_url_host,
'domain[it]' => 'it.example.com',
);
];
$this->drupalPostForm('admin/config/regional/language/detection/url', $edit, t('Save configuration'));
$this->assertText('The configuration options have been saved', 'Domain configuration is saved.');
$this->rebuildContainer();
@ -471,19 +471,19 @@ class LanguageUILanguageNegotiationTest extends WebTestBase {
$italian_url = Url::fromRoute('system.admin', [], ['language' => $languages['it']])->toString();
$url_scheme = \Drupal::request()->isSecure() ? 'https://' : 'http://';
$correct_link = $url_scheme . $link;
$this->assertEqual($italian_url, $correct_link, format_string('The right URL (@url) in accordance with the chosen language', array('@url' => $italian_url)));
$this->assertEqual($italian_url, $correct_link, format_string('The right URL (@url) in accordance with the chosen language', ['@url' => $italian_url]));
// Test HTTPS via options.
$italian_url = Url::fromRoute('system.admin', [], ['https' => TRUE, 'language' => $languages['it']])->toString();
$correct_link = 'https://' . $link;
$this->assertTrue($italian_url == $correct_link, format_string('The right HTTPS URL (via options) (@url) in accordance with the chosen language', array('@url' => $italian_url)));
$this->assertTrue($italian_url == $correct_link, format_string('The right HTTPS URL (via options) (@url) in accordance with the chosen language', ['@url' => $italian_url]));
// Test HTTPS via current URL scheme.
$request = Request::create('', 'GET', array(), array(), array(), array('HTTPS' => 'on'));
$request = Request::create('', 'GET', [], [], [], ['HTTPS' => 'on']);
$this->container->get('request_stack')->push($request);
$italian_url = Url::fromRoute('system.admin', [], ['language' => $languages['it']])->toString();
$correct_link = 'https://' . $link;
$this->assertTrue($italian_url == $correct_link, format_string('The right URL (via current URL scheme) (@url) in accordance with the chosen language', array('@url' => $italian_url)));
$this->assertTrue($italian_url == $correct_link, format_string('The right URL (via current URL scheme) (@url) in accordance with the chosen language', ['@url' => $italian_url]));
}
/**
@ -491,11 +491,11 @@ class LanguageUILanguageNegotiationTest extends WebTestBase {
*/
public function testContentCustomization() {
// Customize content language settings from their defaults.
$edit = array(
$edit = [
'language_content[configurable]' => TRUE,
'language_content[enabled][language-url]' => FALSE,
'language_content[enabled][language-session]' => TRUE,
);
];
$this->drupalPostForm('admin/config/regional/language/detection', $edit, t('Save settings'));
// Check if configurability persisted.
@ -515,16 +515,16 @@ class LanguageUILanguageNegotiationTest extends WebTestBase {
$block_id = 'test_language_block';
// Enable the language switcher block.
$this->drupalPlaceBlock('language_block:' . LanguageInterface::TYPE_CONTENT, array('id' => $block_id));
$this->drupalPlaceBlock('language_block:' . LanguageInterface::TYPE_CONTENT, ['id' => $block_id]);
// Check if the language switcher block has been created.
$block = Block::load($block_id);
$this->assertTrue($block, 'Language switcher block was created.');
// Make sure language_content is not configurable.
$edit = array(
$edit = [
'language_content[configurable]' => FALSE,
);
];
$this->drupalPostForm('admin/config/regional/language/detection', $edit, t('Save settings'));
$this->assertResponse(200);

View file

@ -21,7 +21,7 @@ class LanguageUrlRewritingTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('language', 'language_test');
public static $modules = ['language', 'language_test'];
/**
* An user with permissions to administer languages.
@ -34,16 +34,16 @@ class LanguageUrlRewritingTest extends WebTestBase {
parent::setUp();
// Create and log in user.
$this->webUser = $this->drupalCreateUser(array('administer languages', 'access administration pages'));
$this->webUser = $this->drupalCreateUser(['administer languages', 'access administration pages']);
$this->drupalLogin($this->webUser);
// Install French language.
$edit = array();
$edit = [];
$edit['predefined_langcode'] = 'fr';
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));
// Enable URL language detection and selection.
$edit = array('language_interface[enabled][language-url]' => 1);
$edit = ['language_interface[enabled][language-url]' => 1];
$this->drupalPostForm('admin/config/regional/language/detection', $edit, t('Save settings'));
// Check that drupalSettings contains path prefix.
@ -54,9 +54,9 @@ class LanguageUrlRewritingTest extends WebTestBase {
/**
* Check that non-installed languages are not considered.
*/
function testUrlRewritingEdgeCases() {
public function testUrlRewritingEdgeCases() {
// Check URL rewriting with a non-installed language.
$non_existing = new Language(array('id' => $this->randomMachineName()));
$non_existing = new Language(['id' => $this->randomMachineName()]);
$this->checkUrl($non_existing, 'Path language is ignored if language is not installed.', 'URL language negotiation does not work with non-installed languages');
// Check that URL rewriting is not applied to subrequests.
@ -79,9 +79,9 @@ class LanguageUrlRewritingTest extends WebTestBase {
* The message to display confirming prefixed URL is not working.
*/
private function checkUrl(LanguageInterface $language, $message1, $message2) {
$options = array('language' => $language, 'script' => '');
$options = ['language' => $language, 'script' => ''];
$base_path = trim(base_path(), '/');
$rewritten_path = trim(str_replace($base_path, '', \Drupal::url('<front>', array(), $options)), '/');
$rewritten_path = trim(str_replace($base_path, '', \Drupal::url('<front>', [], $options)), '/');
$segments = explode('/', $rewritten_path, 2);
$prefix = $segments[0];
$path = isset($segments[1]) ? $segments[1] : $prefix;
@ -101,16 +101,16 @@ class LanguageUrlRewritingTest extends WebTestBase {
/**
* Check URL rewriting when using a domain name and a non-standard port.
*/
function testDomainNameNegotiationPort() {
public function testDomainNameNegotiationPort() {
global $base_url;
$language_domain = 'example.fr';
// Get the current host URI we're running on.
$base_url_host = parse_url($base_url, PHP_URL_HOST);
$edit = array(
$edit = [
'language_negotiation_url_part' => LanguageNegotiationUrl::CONFIG_DOMAIN,
'domain[en]' => $base_url_host,
'domain[fr]' => $language_domain
);
];
$this->drupalPostForm('admin/config/regional/language/detection/url', $edit, t('Save configuration'));
// Rebuild the container so that the new language gets picked up by services
// that hold the list of languages.
@ -126,11 +126,11 @@ class LanguageUrlRewritingTest extends WebTestBase {
// In case index.php is part of the URLs, we need to adapt the asserted
// URLs as well.
$index_php = strpos(\Drupal::url('<front>', array(), array('absolute' => TRUE)), 'index.php') !== FALSE;
$index_php = strpos(\Drupal::url('<front>', [], ['absolute' => TRUE]), 'index.php') !== FALSE;
$request = Request::createFromGlobals();
$server = $request->server->all();
$request = $this->prepareRequestForGenerator(TRUE, array('HTTP_HOST' => $server['HTTP_HOST'] . ':88'));
$request = $this->prepareRequestForGenerator(TRUE, ['HTTP_HOST' => $server['HTTP_HOST'] . ':88']);
// Create an absolute French link.
$language = \Drupal::languageManager()->getLanguage('fr');

View file

@ -24,19 +24,19 @@ class LanguageConfigurationElement extends FormBase {
public function buildForm(array $form, FormStateInterface $form_state) {
$conf = ContentLanguageSettings::loadByEntityTypeBundle('entity_test', 'some_bundle');
$form['lang_configuration'] = array(
$form['lang_configuration'] = [
'#type' => 'language_configuration',
'#entity_information' => array(
'#entity_information' => [
'entity_type' => 'entity_test',
'bundle' => 'some_bundle',
),
],
'#default_value' => $conf,
);
];
$form['submit'] = array(
$form['submit'] = [
'#type' => 'submit',
'#value' => 'Save',
);
];
$form['#submit'][] = 'language_configuration_element_submit';
return $form;
}

View file

@ -21,11 +21,11 @@ class LanguageConfigurationElementTest extends FormBase {
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['langcode'] = array(
$form['langcode'] = [
'#title' => t('Language select'),
'#type' => 'language_select',
'#default_value' => language_get_default_langcode('entity_test', 'some_bundle'),
);
];
return $form;
}

View file

@ -6,6 +6,7 @@
*/
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Url;
use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUI;
/**
@ -14,7 +15,7 @@ use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUI;
function language_test_page_top() {
if (\Drupal::moduleHandler()->moduleExists('language')) {
language_test_store_language_negotiation();
drupal_set_message(t('Language negotiation method: @name', array('@name' => \Drupal::languageManager()->getNegotiatedLanguageMethod())));
drupal_set_message(t('Language negotiation method: @name', ['@name' => \Drupal::languageManager()->getNegotiatedLanguageMethod()]));
}
}
@ -23,16 +24,16 @@ function language_test_page_top() {
*/
function language_test_language_types_info() {
if (\Drupal::state()->get('language_test.language_types')) {
return array(
'test_language_type' => array(
return [
'test_language_type' => [
'name' => t('Test'),
'description' => t('A test language type.'),
),
'fixed_test_language_type' => array(
'fixed' => array('test_language_negotiation_method'),
],
'fixed_test_language_type' => [
'fixed' => ['test_language_negotiation_method'],
'locked' => TRUE,
),
);
],
];
}
}
@ -67,7 +68,7 @@ function language_test_language_negotiation_info_alter(array &$negotiation_info)
* Store the last negotiated languages.
*/
function language_test_store_language_negotiation() {
$last = array();
$last = [];
foreach (\Drupal::languageManager()->getDefinedLanguageTypes() as $type) {
$last[$type] = \Drupal::languageManager()->getCurrentLanguage($type)->getId();
}
@ -99,3 +100,10 @@ function language_test_language_fallback_candidates_test_alter(array &$candidate
function language_test_module_preinstall() {
\Drupal::state()->set('language_test.language_count_preinstall', count(\Drupal::languageManager()->getLanguages()));
}
/**
* Implements hook_language_switch_links_alter().
*/
function language_test_language_switch_links_alter(array &$links, $type, Url $url) {
// I'll just sit here and wait to be called with the right arguments.
}

View file

@ -60,7 +60,7 @@ class LanguageTestController implements ContainerInjectionInterface {
* Testing feedback based on (translated) entity title.
*/
public function testEntity(ConfigurableLanguageInterface $configurable_language) {
return array('#markup' => $this->t('Loaded %label.', array('%label' => $configurable_language->label())));
return ['#markup' => $this->t('Loaded %label.', ['%label' => $configurable_language->label()])];
}
/**
@ -72,43 +72,43 @@ class LanguageTestController implements ContainerInjectionInterface {
public function typeLinkActiveClass() {
// We assume that 'en' and 'fr' have been configured.
$languages = $this->languageManager->getLanguages();
return array(
'no_language' => array(
return [
'no_language' => [
'#type' => 'link',
'#title' => t('Link to the current path with no langcode provided.'),
'#url' => Url::fromRoute('<current>'),
'#options' => array(
'attributes' => array(
'#options' => [
'attributes' => [
'id' => 'no_lang_link',
),
],
'set_active_class' => TRUE,
),
),
'fr' => array(
],
],
'fr' => [
'#type' => 'link',
'#title' => t('Link to a French version of the current path.'),
'#url' => Url::fromRoute('<current>'),
'#options' => array(
'#options' => [
'language' => $languages['fr'],
'attributes' => array(
'attributes' => [
'id' => 'fr_link',
),
],
'set_active_class' => TRUE,
),
),
'en' => array(
],
],
'en' => [
'#type' => 'link',
'#title' => t('Link to an English version of the current path.'),
'#url' => Url::fromRoute('<current>'),
'#options' => array(
'#options' => [
'language' => $languages['en'],
'attributes' => array(
'attributes' => [
'id' => 'en_link',
),
],
'set_active_class' => TRUE,
),
),
);
],
],
];
}
/**
@ -130,7 +130,7 @@ class LanguageTestController implements ContainerInjectionInterface {
else {
$base_path = $request->getBasePath();
}
$sub_request = Request::create($base_path . '/user', 'GET', $request->query->all(), $request->cookies->all(), array(), $server);
$sub_request = Request::create($base_path . '/user', 'GET', $request->query->all(), $request->cookies->all(), [], $server);
return $this->httpKernel->handle($sub_request, HttpKernelInterface::SUB_REQUEST);
}

View file

@ -1,25 +1,25 @@
<?php
namespace Drupal\language\Tests;
namespace Drupal\Tests\language\Functional;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\simpletest\WebTestBase;
use Drupal\Tests\BrowserTestBase;
/**
* Test administration path based conversion of entities.
*
* @group language
*/
class AdminPathEntityConverterLanguageTest extends WebTestBase {
class AdminPathEntityConverterLanguageTest extends BrowserTestBase {
public static $modules = array('language', 'language_test');
public static $modules = ['language', 'language_test'];
protected function setUp() {
parent::setUp();
$permissions = array(
$permissions = [
'access administration pages',
'administer site configuration',
);
];
$this->drupalLogin($this->drupalCreateUser($permissions));
ConfigurableLanguage::createFromLangcode('es')->save();
}
@ -34,12 +34,12 @@ class AdminPathEntityConverterLanguageTest extends WebTestBase {
->save();
$this->drupalGet('es/admin/language_test/entity_using_current_language/es');
$this->assertNoRaw(t('Loaded %label.', array('%label' => 'Spanish')));
$this->assertRaw(t('Loaded %label.', array('%label' => 'Español')));
$this->assertNoRaw(t('Loaded %label.', ['%label' => 'Spanish']));
$this->assertRaw(t('Loaded %label.', ['%label' => 'Español']));
$this->drupalGet('es/admin/language_test/entity_using_original_language/es');
$this->assertRaw(t('Loaded %label.', array('%label' => 'Spanish')));
$this->assertNoRaw(t('Loaded %label.', array('%label' => 'Español')));
$this->assertRaw(t('Loaded %label.', ['%label' => 'Spanish']));
$this->assertNoRaw(t('Loaded %label.', ['%label' => 'Español']));
}
}

View file

@ -1,22 +1,22 @@
<?php
namespace Drupal\language\Tests;
namespace Drupal\Tests\language\Functional;
use Drupal\simpletest\WebTestBase;
use Drupal\Tests\BrowserTestBase;
/**
* Tests that the language settings on block config appears correctly.
*
* @group language
*/
class LanguageBlockSettingsVisibilityTest extends WebTestBase {
class LanguageBlockSettingsVisibilityTest extends BrowserTestBase {
public static $modules = array('block', 'language');
public static $modules = ['block', 'language'];
public function testUnnecessaryLanguageSettingsVisibility() {
$admin_user = $this->drupalCreateUser(array('administer languages', 'access administration pages', 'administer blocks'));
$admin_user = $this->drupalCreateUser(['administer languages', 'access administration pages', 'administer blocks']);
$this->drupalLogin($admin_user);
$this->drupalPostForm('admin/config/regional/language/add', array('predefined_langcode' => 'hu'), t('Add language'));
$this->drupalPostForm('admin/config/regional/language/add', ['predefined_langcode' => 'hu'], t('Add language'));
$this->drupalGet('admin/structure/block/add/system_menu_block:admin/stark');
$this->assertNoFieldByXPath('//input[@id="edit-visibility-language-langcodes-und"]', NULL, '\'Not specified\' option does not appear at block config, language settings section.');
$this->assertNoFieldByXpath('//input[@id="edit-visibility-language-langcodes-zxx"]', NULL, '\'Not applicable\' option does not appear at block config, language settings section.');

View file

@ -1,25 +1,25 @@
<?php
namespace Drupal\language\Tests;
namespace Drupal\Tests\language\Functional;
use Drupal\simpletest\WebTestBase;
use Drupal\Tests\BrowserTestBase;
/**
* Tests browser language detection.
*
* @group language
*/
class LanguageBrowserDetectionTest extends WebTestBase {
class LanguageBrowserDetectionTest extends BrowserTestBase {
public static $modules = array('language');
public static $modules = ['language'];
/**
* Tests for adding, editing and deleting mappings between browser language
* codes and Drupal language codes.
*/
function testUIBrowserLanguageMappings() {
public function testUIBrowserLanguageMappings() {
// User to manage languages.
$admin_user = $this->drupalCreateUser(array('administer languages', 'access administration pages'));
$admin_user = $this->drupalCreateUser(['administer languages', 'access administration pages']);
$this->drupalLogin($admin_user);
// Check that the configure link exists.
@ -34,19 +34,19 @@ class LanguageBrowserDetectionTest extends WebTestBase {
// Delete zh-cn language code.
$browser_langcode = 'zh-cn';
$this->drupalGet('admin/config/regional/language/detection/browser/delete/' . $browser_langcode);
$message = t('Are you sure you want to delete @browser_langcode?', array(
$message = t('Are you sure you want to delete @browser_langcode?', [
'@browser_langcode' => $browser_langcode,
));
]);
$this->assertRaw($message);
// Confirm the delete.
$edit = array();
$edit = [];
$this->drupalPostForm('admin/config/regional/language/detection/browser/delete/' . $browser_langcode, $edit, t('Confirm'));
// We need raw here because %browser will add HTML.
$t_args = array(
$t_args = [
'%browser' => $browser_langcode,
);
];
$this->assertRaw(t('The mapping for the %browser browser language code has been deleted.', $t_args), 'The test browser language code has been deleted.');
// Check we went back to the browser negotiation mapping overview.
@ -55,10 +55,10 @@ class LanguageBrowserDetectionTest extends WebTestBase {
$this->assertNoField('edit-mappings-zh-cn-browser-langcode', 'Chinese browser language code no longer exists.');
// Add a new custom mapping.
$edit = array(
$edit = [
'new_mapping[browser_langcode]' => 'xx',
'new_mapping[drupal_langcode]' => 'en',
);
];
$this->drupalPostForm('admin/config/regional/language/detection/browser', $edit, t('Save configuration'));
$this->assertUrl(\Drupal::url('language.negotiation_browser', [], ['absolute' => TRUE]));
$this->assertField('edit-mappings-xx-browser-langcode', 'xx', 'Browser language code found.');
@ -69,18 +69,18 @@ class LanguageBrowserDetectionTest extends WebTestBase {
$this->assertText('Browser language codes must be unique.');
// Change browser language code of our custom mapping to zh-sg.
$edit = array(
$edit = [
'mappings[xx][browser_langcode]' => 'zh-sg',
'mappings[xx][drupal_langcode]' => 'en',
);
];
$this->drupalPostForm('admin/config/regional/language/detection/browser', $edit, t('Save configuration'));
$this->assertText(t('Browser language codes must be unique.'));
// Change Drupal language code of our custom mapping to zh-hans.
$edit = array(
$edit = [
'mappings[xx][browser_langcode]' => 'xx',
'mappings[xx][drupal_langcode]' => 'zh-hans',
);
];
$this->drupalPostForm('admin/config/regional/language/detection/browser', $edit, t('Save configuration'));
$this->assertUrl(\Drupal::url('language.negotiation_browser', [], ['absolute' => TRUE]));
$this->assertField('edit-mappings-xx-browser-langcode', 'xx', 'Browser language code found.');

View file

@ -1,23 +1,23 @@
<?php
namespace Drupal\language\Tests;
namespace Drupal\Tests\language\Functional;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\simpletest\WebTestBase;
use Drupal\Tests\BrowserTestBase;
/**
* Ensures the language config overrides can be synchronized.
*
* @group language
*/
class LanguageConfigOverrideImportTest extends WebTestBase {
class LanguageConfigOverrideImportTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('language', 'config', 'locale', 'config_translation');
public static $modules = ['language', 'config', 'locale', 'config_translation'];
/**
* Tests that language can be enabled and overrides are created during a sync.
@ -31,7 +31,7 @@ class LanguageConfigOverrideImportTest extends WebTestBase {
// Uninstall the language module and its dependencies so we can test
// enabling the language module and creating overrides at the same time
// during a configuration synchronization.
\Drupal::service('module_installer')->uninstall(array('language'));
\Drupal::service('module_installer')->uninstall(['language']);
// Ensure that the current site has no overrides registered to the
// ConfigFactory.
$this->rebuildContainer();
@ -39,8 +39,8 @@ class LanguageConfigOverrideImportTest extends WebTestBase {
/* @var \Drupal\Core\Config\StorageInterface $override_sync */
$override_sync = $sync->createCollection('language.fr');
// Create some overrides in sync.
$override_sync->write('system.site', array('name' => 'FR default site name'));
$override_sync->write('system.maintenance', array('message' => 'FR message: @site is currently under maintenance. We should be back shortly. Thank you for your patience'));
$override_sync->write('system.site', ['name' => 'FR default site name']);
$override_sync->write('system.maintenance', ['message' => 'FR message: @site is currently under maintenance. We should be back shortly. Thank you for your patience']);
$this->configImporter()->import();
$this->rebuildContainer();
@ -61,7 +61,7 @@ class LanguageConfigOverrideImportTest extends WebTestBase {
*/
public function testConfigOverrideImportEvents() {
// Enable the config_events_test module so we can record events occurring.
\Drupal::service('module_installer')->install(array('config_events_test'));
\Drupal::service('module_installer')->install(['config_events_test']);
$this->rebuildContainer();
ConfigurableLanguage::createFromLangcode('fr')->save();
@ -73,7 +73,7 @@ class LanguageConfigOverrideImportTest extends WebTestBase {
/* @var \Drupal\Core\Config\StorageInterface $override_sync */
$override_sync = $sync->createCollection('language.fr');
// Create some overrides in sync.
$override_sync->write('system.site', array('name' => 'FR default site name'));
$override_sync->write('system.site', ['name' => 'FR default site name']);
\Drupal::state()->set('config_events_test.event', FALSE);
$this->configImporter()->import();

View file

@ -1,16 +1,16 @@
<?php
namespace Drupal\language\Tests;
namespace Drupal\Tests\language\Functional;
use Drupal\config\Tests\SchemaCheckTestTrait;
use Drupal\simpletest\WebTestBase;
use Drupal\Tests\SchemaCheckTestTrait;
use Drupal\Tests\BrowserTestBase;
/**
* Ensures the language config schema is correct.
*
* @group language
*/
class LanguageConfigSchemaTest extends WebTestBase {
class LanguageConfigSchemaTest extends BrowserTestBase {
use SchemaCheckTestTrait;
@ -19,7 +19,7 @@ class LanguageConfigSchemaTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('language', 'menu_link_content');
public static $modules = ['language', 'menu_link_content'];
/**
* A user with administrative permissions.
@ -35,14 +35,14 @@ class LanguageConfigSchemaTest extends WebTestBase {
parent::setUp();
// Create user.
$this->adminUser = $this->drupalCreateUser(array('administer languages'));
$this->adminUser = $this->drupalCreateUser(['administer languages']);
$this->drupalLogin($this->adminUser);
}
/**
* Tests whether the language config schema is valid.
*/
function testValidLanguageConfigSchema() {
public function testValidLanguageConfigSchema() {
// Make sure no language configuration available by default.
$config_data = $this->config('language.settings')->get();
$this->assertTrue(empty($config_data));

View file

@ -1,8 +1,8 @@
<?php
namespace Drupal\language\Tests;
namespace Drupal\Tests\language\Functional;
use Drupal\simpletest\WebTestBase;
use Drupal\Tests\BrowserTestBase;
/**
* Tests enabling Language if a module exists that calls
@ -10,25 +10,25 @@ use Drupal\simpletest\WebTestBase;
*
* @group language
*/
class LanguageListModuleInstallTest extends WebTestBase {
class LanguageListModuleInstallTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('language_test');
public static $modules = ['language_test'];
/**
* Tests enabling Language.
*/
function testModuleInstallLanguageList() {
public function testModuleInstallLanguageList() {
// Since LanguageManager::getLanguages() uses static caches we need to do
// this by enabling the module using the UI.
$admin_user = $this->drupalCreateUser(array('access administration pages', 'administer modules'));
$admin_user = $this->drupalCreateUser(['access administration pages', 'administer modules']);
$this->drupalLogin($admin_user);
$edit = array();
$edit['modules[Multilingual][language][enable]'] = 'language';
$edit = [];
$edit['modules[language][enable]'] = 'language';
$this->drupalPostForm('admin/modules', $edit, t('Install'));
$this->assertEqual(\Drupal::state()->get('language_test.language_count_preinstall', 0), 1, 'Using LanguageManager::getLanguages() returns 1 language during Language installation.');

View file

@ -1,6 +1,6 @@
<?php
namespace Drupal\language\Tests;
namespace Drupal\Tests\language\Functional;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\Language\LanguageInterface;
@ -8,7 +8,7 @@ use Drupal\entity_test\Entity\EntityTest;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationContentEntity;
use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl;
use Drupal\simpletest\WebTestBase;
use Drupal\Tests\BrowserTestBase;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Route;
@ -18,14 +18,14 @@ use Symfony\Component\Routing\Route;
*
* @group language
*/
class LanguageNegotiationContentEntityTest extends WebTestBase {
class LanguageNegotiationContentEntityTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('language', 'language_test', 'entity_test', 'system');
public static $modules = ['language', 'language_test', 'entity_test', 'system'];
/**
* The entity being used for testing.
@ -49,7 +49,7 @@ class LanguageNegotiationContentEntityTest extends WebTestBase {
$this->createTranslatableEntity();
$user = $this->drupalCreateUser(array('view test entity'));
$user = $this->drupalCreateUser(['view test entity']);
$this->drupalLogin($user);
}

View file

@ -1,17 +1,17 @@
<?php
namespace Drupal\language\Tests;
namespace Drupal\Tests\language\Functional;
use Drupal\Core\Language\LanguageInterface;
use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUI;
use Drupal\simpletest\WebTestBase;
use Drupal\Tests\BrowserTestBase;
/**
* Tests alterations to language types/negotiation info.
*
* @group language
*/
class LanguageNegotiationInfoTest extends WebTestBase {
class LanguageNegotiationInfoTest extends BrowserTestBase {
/**
* Modules to enable.
@ -27,7 +27,7 @@ class LanguageNegotiationInfoTest extends WebTestBase {
parent::setUp();
$admin_user = $this->drupalCreateUser(['administer languages', 'access administration pages', 'view the administration theme', 'administer modules']);
$this->drupalLogin($admin_user);
$this->drupalPostForm('admin/config/regional/language/add', array('predefined_langcode' => 'it'), t('Add language'));
$this->drupalPostForm('admin/config/regional/language/add', ['predefined_langcode' => 'it'], t('Add language'));
}
/**
@ -61,16 +61,16 @@ class LanguageNegotiationInfoTest extends WebTestBase {
/**
* Tests alterations to language types/negotiation info.
*/
function testInfoAlterations() {
$this->stateSet(array(
public function testInfoAlterations() {
$this->stateSet([
// Enable language_test type info.
'language_test.language_types' => TRUE,
// Enable language_test negotiation info (not altered yet).
'language_test.language_negotiation_info' => TRUE,
// Alter LanguageInterface::TYPE_CONTENT to be configurable.
'language_test.content_language_type' => TRUE,
));
$this->container->get('module_installer')->install(array('language_test'));
]);
$this->container->get('module_installer')->install(['language_test']);
$this->resetAll();
// Check that fixed language types are properly configured without the need
@ -87,19 +87,19 @@ class LanguageNegotiationInfoTest extends WebTestBase {
$interface_method_id = LanguageNegotiationUI::METHOD_ID;
$test_method_id = 'test_language_negotiation_method';
$form_field = $type . '[enabled][' . $interface_method_id . ']';
$edit = array(
$edit = [
$form_field => TRUE,
$type . '[enabled][' . $test_method_id . ']' => TRUE,
$test_type . '[enabled][' . $test_method_id . ']' => TRUE,
$test_type . '[configurable]' => TRUE,
);
];
$this->drupalPostForm('admin/config/regional/language/detection', $edit, t('Save settings'));
// Alter language negotiation info to remove interface language negotiation
// method.
$this->stateSet(array(
$this->stateSet([
'language_test.language_negotiation_info_alter' => TRUE,
));
]);
$negotiation = $this->config('language.types')->get('negotiation.' . $type . '.enabled');
$this->assertFalse(isset($negotiation[$interface_method_id]), 'Interface language negotiation method removed from the stored settings.');
@ -112,10 +112,10 @@ class LanguageNegotiationInfoTest extends WebTestBase {
foreach ($this->languageManager()->getLanguageTypes() as $type) {
$form_field = $type . '[enabled][test_language_negotiation_method_ts]';
if ($type == $test_type) {
$this->assertFieldByName($form_field, NULL, format_string('Type-specific test language negotiation method available for %type.', array('%type' => $type)));
$this->assertFieldByName($form_field, NULL, format_string('Type-specific test language negotiation method available for %type.', ['%type' => $type]));
}
else {
$this->assertNoFieldByName($form_field, NULL, format_string('Type-specific test language negotiation method unavailable for %type.', array('%type' => $type)));
$this->assertNoFieldByName($form_field, NULL, format_string('Type-specific test language negotiation method unavailable for %type.', ['%type' => $type]));
}
}
@ -125,17 +125,17 @@ class LanguageNegotiationInfoTest extends WebTestBase {
foreach ($this->languageManager()->getDefinedLanguageTypes() as $type) {
$langcode = $last[$type];
$value = $type == LanguageInterface::TYPE_CONTENT || strpos($type, 'test') !== FALSE ? 'it' : 'en';
$this->assertEqual($langcode, $value, format_string('The negotiated language for %type is %language', array('%type' => $type, '%language' => $value)));
$this->assertEqual($langcode, $value, format_string('The negotiated language for %type is %language', ['%type' => $type, '%language' => $value]));
}
// Uninstall language_test and check that everything is set back to the
// original status.
$this->container->get('module_installer')->uninstall(array('language_test'));
$this->container->get('module_installer')->uninstall(['language_test']);
$this->rebuildContainer();
// Check that only the core language types are available.
foreach ($this->languageManager()->getDefinedLanguageTypes() as $type) {
$this->assertTrue(strpos($type, 'test') === FALSE, format_string('The %type language is still available', array('%type' => $type)));
$this->assertTrue(strpos($type, 'test') === FALSE, format_string('The %type language is still available', ['%type' => $type]));
}
// Check that fixed language types are properly configured, even those
@ -165,7 +165,7 @@ class LanguageNegotiationInfoTest extends WebTestBase {
list(, $info_id) = each($info['fixed']);
$equal = $info_id == $id;
}
$this->assertTrue($equal, format_string('language negotiation for %type is properly set up', array('%type' => $type)));
$this->assertTrue($equal, format_string('language negotiation for %type is properly set up', ['%type' => $type]));
}
}
}
@ -184,7 +184,7 @@ class LanguageNegotiationInfoTest extends WebTestBase {
$this->assertTrue($this->isLanguageTypeConfigurable($test_type), 'Language type is now configurable.');
// After installing another module, the config should be the same.
$this->drupalPostForm('admin/modules', ['modules[Testing][test_module][enable]' => 1], t('Install'));
$this->drupalPostForm('admin/modules', ['modules[test_module][enable]' => 1], t('Install'));
$this->assertTrue($this->isLanguageTypeConfigurable($test_type), 'Language type is still configurable.');
// After uninstalling the other module, the config should be the same.

View file

@ -0,0 +1,77 @@
<?php
namespace Drupal\Tests\language\Functional;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Tests\BrowserTestBase;
/**
* @coversDefaultClass \Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl
* @group language
*/
class LanguageNegotiationUrlTest extends BrowserTestBase {
use StringTranslationTrait;
/**
* {@inheritdoc}
*/
public static $modules = [
'language',
'node',
'path',
];
/**
* @var \Drupal\user\Entity\User
*/
protected $user;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// Create an Article node type.
if ($this->profile != 'standard') {
$this->drupalCreateContentType(['type' => 'article']);
}
$this->user = $this->drupalCreateUser([
'administer languages',
'access administration pages',
'view the administration theme',
'administer nodes',
'create article content',
'create url aliases',
]);
$this->drupalLogin($this->user);
$this->drupalPostForm('admin/config/regional/language/add', ['predefined_langcode' => 'de'], $this->t('Add language'));
}
/**
* @covers ::processInbound
*/
public function testDomain() {
// Check if paths that contain language prefixes can be reached when
// language is taken from the domain.
$edit = [
'language_negotiation_url_part' => 'domain',
'prefix[en]' => 'eng',
'prefix[de]' => 'de',
'domain[en]' => $_SERVER['HTTP_HOST'],
'domain[de]' => "de.$_SERVER[HTTP_HOST]",
];
$this->drupalPostForm('admin/config/regional/language/detection/url', $edit, $this->t('Save configuration'));
$nodeValues = [
'title[0][value]' => 'Test',
'path[0][alias]' => '/eng/test',
];
$this->drupalPostForm('node/add/article', $nodeValues, $this->t('Save and publish'));
$this->assertSession()->statusCodeEquals(200);
}
}

View file

@ -1,15 +1,15 @@
<?php
namespace Drupal\language\Tests;
namespace Drupal\Tests\language\Functional;
use Drupal\simpletest\WebTestBase;
use Drupal\Tests\BrowserTestBase;
/**
* Confirm that paths are not changed on monolingual non-English sites.
*
* @group language
*/
class LanguagePathMonolingualTest extends WebTestBase {
class LanguagePathMonolingualTest extends BrowserTestBase {
/**
* Modules to enable.
@ -22,22 +22,22 @@ class LanguagePathMonolingualTest extends WebTestBase {
parent::setUp();
// Create and log in user.
$web_user = $this->drupalCreateUser(array('administer languages', 'access administration pages', 'administer site configuration'));
$web_user = $this->drupalCreateUser(['administer languages', 'access administration pages', 'administer site configuration']);
$this->drupalLogin($web_user);
// Enable French language.
$edit = array();
$edit = [];
$edit['predefined_langcode'] = 'fr';
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));
// Make French the default language.
$edit = array(
$edit = [
'site_default_language' => 'fr',
);
];
$this->drupalPostForm('admin/config/regional/language', $edit, t('Save configuration'));
// Delete English.
$this->drupalPostForm('admin/config/regional/language/delete/en', array(), t('Delete'));
$this->drupalPostForm('admin/config/regional/language/delete/en', [], t('Delete'));
// Changing the default language causes a container rebuild. Therefore need
// to rebuild the container in the test environment.
@ -49,7 +49,7 @@ class LanguagePathMonolingualTest extends WebTestBase {
$this->assertEqual(\Drupal::languageManager()->getDefaultLanguage()->getId(), 'fr', 'French is the default language');
// Set language detection to URL.
$edit = array('language_interface[enabled][language-url]' => TRUE);
$edit = ['language_interface[enabled][language-url]' => TRUE];
$this->drupalPostForm('admin/config/regional/language/detection', $edit, t('Save settings'));
$this->drupalPlaceBlock('local_actions_block');
}
@ -57,7 +57,7 @@ class LanguagePathMonolingualTest extends WebTestBase {
/**
* Verifies that links do not have language prefixes in them.
*/
function testPageLinks() {
public function testPageLinks() {
// Navigate to 'admin/config' path.
$this->drupalGet('admin/config');

View file

@ -1,6 +1,6 @@
<?php
namespace Drupal\language\Tests\Migrate;
namespace Drupal\Tests\language\Functional\Migrate;
use Drupal\language\ConfigurableLanguageInterface;
use Drupal\language\Entity\ConfigurableLanguage;

View file

@ -32,12 +32,12 @@ class LanguageConditionTest extends KernelTestBase {
*
* @var array
*/
public static $modules = array('system', 'language');
public static $modules = ['system', 'language'];
protected function setUp() {
parent::setUp();
$this->installConfig(array('language'));
$this->installConfig(['language']);
// Setup Italian.
ConfigurableLanguage::createFromLangcode('it')->save();
@ -52,14 +52,14 @@ class LanguageConditionTest extends KernelTestBase {
// language.
$language = \Drupal::languageManager()->getLanguage('en');
$condition = $this->manager->createInstance('language')
->setConfig('langcodes', array('en' => 'en', 'it' => 'it'))
->setConfig('langcodes', ['en' => 'en', 'it' => 'it'])
->setContextValue('language', $language);
$this->assertTrue($condition->execute(), 'Language condition passes as expected.');
// Check for the proper summary.
$this->assertEqual($condition->summary(), 'The language is English, Italian.');
// Change to Italian only.
$condition->setConfig('langcodes', array('it' => 'it'));
$condition->setConfig('langcodes', ['it' => 'it']);
$this->assertFalse($condition->execute(), 'Language condition fails as expected.');
// Check for the proper summary.
$this->assertEqual($condition->summary(), 'The language is Italian.');
@ -74,7 +74,7 @@ class LanguageConditionTest extends KernelTestBase {
$language = \Drupal::languageManager()->getLanguage('it');
$condition = $this->manager->createInstance('language')
->setConfig('langcodes', array('en' => 'en', 'it' => 'it'))
->setConfig('langcodes', ['en' => 'en', 'it' => 'it'])
->setContextValue('language', $language);
$this->assertTrue($condition->execute(), 'Language condition passes as expected.');
@ -82,7 +82,7 @@ class LanguageConditionTest extends KernelTestBase {
$this->assertEqual($condition->summary(), 'The language is English, Italian.');
// Change to Italian only.
$condition->setConfig('langcodes', array('it' => 'it'));
$condition->setConfig('langcodes', ['it' => 'it']);
$this->assertTrue($condition->execute(), 'Language condition passes as expected.');
// Check for the proper summary.
$this->assertEqual($condition->summary(), 'The language is Italian.');

View file

@ -0,0 +1,56 @@
<?php
namespace Drupal\Tests\language\Kernel;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Url;
/**
* Tests the ConfigurableLanguage entity.
*
* @group language
* @coversDefaultClass \Drupal\language\ConfigurableLanguageManager
*/
class ConfigurableLanguageManagerTest extends LanguageTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['user'];
/**
* The language negotiator.
*
* @var \Drupal\language\LanguageNegotiatorInterface
*/
protected $languageNegotiator;
/**
* The language manager.
*
* @var \Drupal\language\ConfigurableLanguageManagerInterface
*/
protected $languageManager;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installSchema('system', ['sequence']);
$this->installEntitySchema('user');
$this->languageNegotiator = $this->container->get('language_negotiator');
$this->languageManager = $this->container->get('language_manager');
}
/**
* @covers ::getLanguageSwitchLinks
*/
public function testLanguageSwitchLinks() {
$this->languageNegotiator->setCurrentUser($this->prophesize('Drupal\Core\Session\AccountInterface')->reveal());
$this->languageManager->getLanguageSwitchLinks(LanguageInterface::TYPE_INTERFACE, new Url('<current>'));
}
}

View file

@ -18,7 +18,7 @@ class ConfigurableLanguageTest extends KernelTestBase {
*
* @var array
*/
public static $modules = array('language');
public static $modules = ['language'];
/**
* Tests configurable language name methods.
@ -26,7 +26,7 @@ class ConfigurableLanguageTest extends KernelTestBase {
public function testName() {
$name = $this->randomMachineName();
$language_code = $this->randomMachineName(2);
$configurableLanguage = new ConfigurableLanguage(array('label' => $name, 'id' => $language_code), 'configurable_language');
$configurableLanguage = new ConfigurableLanguage(['label' => $name, 'id' => $language_code], 'configurable_language');
$this->assertEqual($configurableLanguage->getName(), $name);
$this->assertEqual($configurableLanguage->setName('Test language')->getName(), 'Test language');
}

View file

@ -18,7 +18,7 @@ class EntityDefaultLanguageTest extends KernelTestBase {
*
* @var array
*/
public static $modules = array('language', 'node', 'field', 'text', 'user', 'system');
public static $modules = ['language', 'node', 'field', 'text', 'user', 'system'];
/**
* {@inheritdoc}
@ -29,9 +29,9 @@ class EntityDefaultLanguageTest extends KernelTestBase {
$this->installEntitySchema('user');
// Activate Spanish language, so there are two languages activated.
$language = $this->container->get('entity.manager')->getStorage('configurable_language')->create(array(
$language = $this->container->get('entity.manager')->getStorage('configurable_language')->create([
'id' => 'es',
));
]);
$language->save();
// Create a new content type which has Undefined language by default.
@ -67,7 +67,7 @@ class EntityDefaultLanguageTest extends KernelTestBase {
$this->assertEqual($node->langcode->value, 'en');
// Disable language module.
$this->disableModules(array('language'));
$this->disableModules(['language']);
// With language module disabled, and a content type that is configured to
// have no language specified by default, a new node of this content type
@ -101,12 +101,12 @@ class EntityDefaultLanguageTest extends KernelTestBase {
* Default language code of the nodes of this type.
*/
protected function createContentType($name, $langcode) {
$content_type = $this->container->get('entity.manager')->getStorage('node_type')->create(array(
$content_type = $this->container->get('entity.manager')->getStorage('node_type')->create([
'name' => 'Test ' . $name,
'title_label' => 'Title',
'type' => $name,
'create_body' => FALSE,
));
]);
$content_type->save();
ContentLanguageSettings::loadByEntityTypeBundle('node', $name)
->setLanguageAlterable(FALSE)
@ -127,10 +127,10 @@ class EntityDefaultLanguageTest extends KernelTestBase {
* The node created.
*/
protected function createNode($type, $langcode = NULL) {
$values = array(
$values = [
'type' => $type,
'title' => $this->randomString(),
);
];
if (!empty($langcode)) {
$values['langcode'] = $langcode;
}

View file

@ -0,0 +1,43 @@
<?php
namespace Drupal\Tests\language\Kernel;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\KernelTests\KernelTestBase;
/**
* Tests \Drupal\language\Config\LanguageConfigFactoryOverride.
*
* @group language
*/
class LanguageConfigFactoryOverrideTest extends KernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['system', 'language'];
/**
* Tests language.config_factory_override service has the default language.
*/
public function testLanguageConfigFactoryOverride() {
$this->installConfig('system');
$this->installConfig('language');
/** @var \Drupal\language\Config\LanguageConfigFactoryOverride $config_factory_override */
$config_factory_override = \Drupal::service('language.config_factory_override');
$this->assertEquals('en', $config_factory_override->getLanguage()->getId());
ConfigurableLanguage::createFromLangcode('de')->save();
// Invalidate the container.
$this->config('system.site')->set('default_langcode', 'de')->save();
drupal_flush_all_caches();
$config_factory_override = \Drupal::service('language.config_factory_override');
$this->assertEquals('de', $config_factory_override->getLanguage()->getId());
}
}

View file

@ -17,7 +17,7 @@ class LanguageConfigOverrideInstallTest extends KernelTestBase {
*
* @var array
*/
public static $modules = array('language', 'config_events_test');
public static $modules = ['language', 'config_events_test'];
/**
* Tests the configuration events are not fired during install of overrides.
@ -26,9 +26,9 @@ class LanguageConfigOverrideInstallTest extends KernelTestBase {
ConfigurableLanguage::createFromLangcode('de')->save();
// Need to enable test module after creating the language otherwise saving
// the language will install the configuration.
$this->enableModules(array('language_config_override_test'));
$this->enableModules(['language_config_override_test']);
\Drupal::state()->set('config_events_test.event', FALSE);
$this->installConfig(array('language_config_override_test'));
$this->installConfig(['language_config_override_test']);
$event_recorder = \Drupal::state()->get('config_events_test.event', FALSE);
$this->assertFalse($event_recorder);
$config = \Drupal::service('language.config_factory_override')->getOverride('de', 'language_config_override_test.settings');

View file

@ -18,11 +18,11 @@ class LanguageDependencyInjectionTest extends LanguageTestBase {
*
* @see \Drupal\Core\Language\LanguageInterface
*/
function testDependencyInjectedNewLanguage() {
public function testDependencyInjectedNewLanguage() {
$expected = $this->languageManager->getDefaultLanguage();
$result = $this->languageManager->getCurrentLanguage();
foreach ($expected as $property => $value) {
$this->assertEqual($expected->$property, $result->$property, format_string('The dependency injected language object %prop property equals the new Language object %prop property.', array('%prop' => $property)));
$this->assertEqual($expected->$property, $result->$property, format_string('The dependency injected language object %prop property equals the new Language object %prop property.', ['%prop' => $property]));
}
}
@ -32,7 +32,7 @@ class LanguageDependencyInjectionTest extends LanguageTestBase {
*
* @see \Drupal\Core\Language\Language
*/
function testDependencyInjectedNewDefaultLanguage() {
public function testDependencyInjectedNewDefaultLanguage() {
$default_language = ConfigurableLanguage::load(\Drupal::languageManager()->getDefaultLanguage()->getId());
// Change the language default object to different values.
ConfigurableLanguage::createFromLangcode('fr')->save();
@ -45,7 +45,7 @@ class LanguageDependencyInjectionTest extends LanguageTestBase {
// Delete the language to check that we fallback to the default.
try {
entity_delete_multiple('configurable_language', array('fr'));
entity_delete_multiple('configurable_language', ['fr']);
$this->fail('Expected DeleteDefaultLanguageException thrown.');
}
catch (DeleteDefaultLanguageException $e) {
@ -55,7 +55,7 @@ class LanguageDependencyInjectionTest extends LanguageTestBase {
// Re-save the previous default language and the delete should work.
$this->config('system.site')->set('default_langcode', $default_language->getId())->save();
entity_delete_multiple('configurable_language', array('fr'));
entity_delete_multiple('configurable_language', ['fr']);
$result = \Drupal::languageManager()->getCurrentLanguage();
$this->assertIdentical($result->getId(), $default_language->getId());
}

View file

@ -19,7 +19,7 @@ class LanguageFallbackTest extends LanguageTestBase {
parent::setUp();
$i = 0;
foreach (array('af', 'am', 'ar') as $langcode) {
foreach (['af', 'am', 'ar'] as $langcode) {
$language = ConfigurableLanguage::createFromLangcode($langcode);
$language->set('weight', $i--);
$language->save();
@ -31,7 +31,7 @@ class LanguageFallbackTest extends LanguageTestBase {
*/
public function testCandidates() {
$language_list = $this->languageManager->getLanguages();
$expected = array_keys($language_list + array(LanguageInterface::LANGCODE_NOT_SPECIFIED => NULL));
$expected = array_keys($language_list + [LanguageInterface::LANGCODE_NOT_SPECIFIED => NULL]);
// Check that language fallback candidates by default are all the available
// languages sorted by weight.
@ -49,11 +49,11 @@ class LanguageFallbackTest extends LanguageTestBase {
$this->state->set('language_test.fallback_operation_alter.candidates', TRUE);
$expected[] = LanguageInterface::LANGCODE_NOT_SPECIFIED;
$expected[] = LanguageInterface::LANGCODE_NOT_APPLICABLE;
$candidates = $this->languageManager->getFallbackCandidates(array('operation' => 'test'));
$candidates = $this->languageManager->getFallbackCandidates(['operation' => 'test']);
$this->assertEqual(array_values($candidates), $expected, 'Language fallback candidates are alterable for specific operations.');
// Check that when the site is monolingual no language fallback is applied.
$langcodes_to_delete = array();
$langcodes_to_delete = [];
foreach ($language_list as $langcode => $language) {
if (!$language->isDefault()) {
$langcodes_to_delete[] = $langcode;
@ -61,7 +61,7 @@ class LanguageFallbackTest extends LanguageTestBase {
}
entity_delete_multiple('configurable_language', $langcodes_to_delete);
$candidates = $this->languageManager->getFallbackCandidates();
$this->assertEqual(array_values($candidates), array(LanguageInterface::LANGCODE_DEFAULT), 'Language fallback is not applied when the Language module is not enabled.');
$this->assertEqual(array_values($candidates), [LanguageInterface::LANGCODE_DEFAULT], 'Language fallback is not applied when the Language module is not enabled.');
}
}

View file

@ -9,7 +9,7 @@ use Drupal\KernelTests\KernelTestBase;
*/
abstract class LanguageTestBase extends KernelTestBase {
public static $modules = array('system', 'language', 'language_test');
public static $modules = ['system', 'language', 'language_test'];
/**
* The language manager.
*
@ -30,7 +30,7 @@ abstract class LanguageTestBase extends KernelTestBase {
protected function setUp() {
parent::setUp();
$this->installConfig(array('language'));
$this->installConfig(['language']);
$this->state = $this->container->get('state');

View file

@ -24,9 +24,9 @@ trait MigrateDefaultLanguageTrait {
// default language is migrated.
$value = 'O:8:"stdClass":11:{s:8:"language";s:2:"' . $langcode . '";s:4:"name";s:6:"French";s:6:"native";s:6:"French";s:9:"direction";s:1:"0";s:7:"enabled";i:1;s:7:"plurals";s:1:"0";s:7:"formula";s:0:"";s:6:"domain";s:0:"";s:6:"prefix";s:0:"";s:6:"weight";s:1:"0";s:10:"javascript";s:0:"";}';
$this->sourceDatabase->update('variable')
->fields(array(
->fields([
'value' => $value
))
])
->condition('name', 'language_default' )
->execute();

View file

@ -56,7 +56,7 @@ class MigrateLanguageNegotiationSettingsTest extends MigrateDrupal6TestBase {
*/
public function testLanguageNegotiationWithNoNegotiation() {
$this->sourceDatabase->update('variable')
->fields(array('value' => serialize(0)))
->fields(['value' => serialize(0)])
->condition('name', 'language_negotiation')
->execute();
@ -88,7 +88,7 @@ class MigrateLanguageNegotiationSettingsTest extends MigrateDrupal6TestBase {
*/
public function testLanguageNegotiationWithPathPrefix() {
$this->sourceDatabase->update('variable')
->fields(array('value' => serialize(2)))
->fields(['value' => serialize(2)])
->condition('name', 'language_negotiation')
->execute();
@ -129,7 +129,7 @@ class MigrateLanguageNegotiationSettingsTest extends MigrateDrupal6TestBase {
*/
public function testLanguageNegotiationWithDomain() {
$this->sourceDatabase->update('variable')
->fields(array('value' => serialize(3)))
->fields(['value' => serialize(3)])
->condition('name', 'language_negotiation')
->execute();

View file

@ -75,7 +75,7 @@ class MigrateLanguageNegotiationSettingsTest extends MigrateDrupal7TestBase {
*/
public function testLanguageNegotiationWithDomain() {
$this->sourceDatabase->update('variable')
->fields(array('value' => serialize(1)))
->fields(['value' => serialize(1)])
->condition('name', 'locale_language_negotiation_url_part')
->execute();

View file

@ -0,0 +1,89 @@
<?php
namespace Drupal\Tests\language\Kernel\Plugin\migrate\source;
use Drupal\Tests\migrate\Kernel\MigrateSqlSourceTestBase;
/**
* Tests the language source plugin.
*
* @covers \Drupal\language\Plugin\migrate\source\Language
* @group language
*/
class LanguageTest extends MigrateSqlSourceTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['language', 'migrate_drupal'];
/**
* {@inheritdoc}
*/
public function providerSource() {
$tests = [];
// The source data.
$tests[0]['source_data']['languages'] = [
[
'language' => 'en',
'name' => 'English',
'native' => 'English',
'direction' => '0',
'enabled' => '1',
'plurals' => '0',
'formula' => '',
'domain' => '',
'prefix' => '',
'weight' => '0',
'javascript' => '',
],
[
'language' => 'fr',
'name' => 'French',
'native' => 'Français',
'direction' => '0',
'enabled' => '0',
'plurals' => '2',
'formula' => '($n>1)',
'domain' => '',
'prefix' => 'fr',
'weight' => '0',
'javascript' => '',
],
];
// The expected results.
$tests[0]['expected_data'] = [
[
'language' => 'en',
'name' => 'English',
'native' => 'English',
'direction' => '0',
'enabled' => '1',
'plurals' => '0',
'formula' => '',
'domain' => '',
'prefix' => '',
'weight' => '0',
'javascript' => '',
],
[
'language' => 'fr',
'name' => 'French',
'native' => 'Français',
'direction' => '0',
'enabled' => '0',
'plurals' => '2',
'formula' => '($n>1)',
'domain' => '',
'prefix' => 'fr',
'weight' => '0',
'javascript' => '',
],
];
return $tests;
}
}

View file

@ -17,28 +17,28 @@ class ArgumentLanguageTest extends LanguageTestBase {
*
* @var array
*/
public static $testViews = array('test_view');
public static $testViews = ['test_view'];
/**
* Tests the language argument.
*/
public function testArgument() {
$view = Views::getView('test_view');
foreach (array('en' => 'John', 'xx-lolspeak' => 'George') as $langcode => $name) {
foreach (['en' => 'John', 'xx-lolspeak' => 'George'] as $langcode => $name) {
$view->setDisplay();
$view->displayHandlers->get('default')->overrideOption('arguments', array(
'langcode' => array(
$view->displayHandlers->get('default')->overrideOption('arguments', [
'langcode' => [
'id' => 'langcode',
'table' => 'views_test_data',
'field' => 'langcode',
),
));
$this->executeView($view, array($langcode));
],
]);
$this->executeView($view, [$langcode]);
$expected = array(array(
$expected = [[
'name' => $name,
));
$this->assertIdenticalResultset($view, $expected, array('views_test_data_name' => 'name'));
]];
$this->assertIdenticalResultset($view, $expected, ['views_test_data_name' => 'name']);
$view->destroy();
}
}

View file

@ -17,7 +17,7 @@ class FieldLanguageTest extends LanguageTestBase {
*
* @var array
*/
public static $testViews = array('test_view');
public static $testViews = ['test_view'];
/**
* Tests the language field.
@ -25,13 +25,13 @@ class FieldLanguageTest extends LanguageTestBase {
public function testField() {
$view = Views::getView('test_view');
$view->setDisplay();
$view->displayHandlers->get('default')->overrideOption('fields', array(
'langcode' => array(
$view->displayHandlers->get('default')->overrideOption('fields', [
'langcode' => [
'id' => 'langcode',
'table' => 'views_test_data',
'field' => 'langcode',
),
));
],
]);
$this->executeView($view);
$this->assertEqual($view->field['langcode']->advancedRender($view->result[0]), 'English');

View file

@ -17,29 +17,29 @@ class FilterLanguageTest extends LanguageTestBase {
*
* @var array
*/
public static $testViews = array('test_view');
public static $testViews = ['test_view'];
/**
* Tests the language filter.
*/
public function testFilter() {
$view = Views::getView('test_view');
foreach (array('en' => 'John', 'xx-lolspeak' => 'George') as $langcode => $name) {
foreach (['en' => 'John', 'xx-lolspeak' => 'George'] as $langcode => $name) {
$view->setDisplay();
$view->displayHandlers->get('default')->overrideOption('filters', array(
'langcode' => array(
$view->displayHandlers->get('default')->overrideOption('filters', [
'langcode' => [
'id' => 'langcode',
'table' => 'views_test_data',
'field' => 'langcode',
'value' => array($langcode),
),
));
'value' => [$langcode],
],
]);
$this->executeView($view);
$expected = array(array(
$expected = [[
'name' => $name,
));
$this->assertIdenticalResultset($view, $expected, array('views_test_data_name' => 'name'));
]];
$this->assertIdenticalResultset($view, $expected, ['views_test_data_name' => 'name']);
$expected = [
'***LANGUAGE_site_default***',

View file

@ -15,14 +15,14 @@ abstract class LanguageTestBase extends ViewsKernelTestBase {
*
* @var array
*/
public static $modules = array('system', 'language');
public static $modules = ['system', 'language'];
protected function setUp($import_test_views = TRUE) {
parent::setUp();
$this->installConfig(array('language'));
$this->installConfig(['language']);
// Create another language beside English.
ConfigurableLanguage::create(array('id' => 'xx-lolspeak', 'label' => 'Lolspeak'))->save();
ConfigurableLanguage::create(['id' => 'xx-lolspeak', 'label' => 'Lolspeak'])->save();
}
/**
@ -30,12 +30,12 @@ abstract class LanguageTestBase extends ViewsKernelTestBase {
*/
protected function schemaDefinition() {
$schema = parent::schemaDefinition();
$schema['views_test_data']['fields']['langcode'] = array(
$schema['views_test_data']['fields']['langcode'] = [
'description' => 'The {language}.langcode of this beatle.',
'type' => 'varchar',
'length' => 12,
'default' => '',
);
];
return $schema;
}
@ -45,19 +45,19 @@ abstract class LanguageTestBase extends ViewsKernelTestBase {
*/
protected function viewsData() {
$data = parent::viewsData();
$data['views_test_data']['langcode'] = array(
$data['views_test_data']['langcode'] = [
'title' => t('Langcode'),
'help' => t('Langcode'),
'field' => array(
'field' => [
'id' => 'language',
),
'argument' => array(
],
'argument' => [
'id' => 'language',
),
'filter' => array(
],
'filter' => [
'id' => 'language',
),
);
],
];
return $data;
}

View file

@ -21,11 +21,11 @@ class ConfigurableLanguageUnitTest extends UnitTestCase {
// Direction of language writing, an integer. Usually either
// ConfigurableLanguage::DIRECTION_LTR or
// ConfigurableLanguage::DIRECTION_RTL.
$configurableLanguage = new ConfigurableLanguage(array('direction' => ConfigurableLanguage::DIRECTION_LTR), 'configurable_language');
$configurableLanguage = new ConfigurableLanguage(['direction' => ConfigurableLanguage::DIRECTION_LTR], 'configurable_language');
$this->assertEquals(ConfigurableLanguage::DIRECTION_LTR, $configurableLanguage->getDirection());
// Test direction again, setting direction to RTL.
$configurableLanguage = new ConfigurableLanguage(array('direction' => ConfigurableLanguage::DIRECTION_RTL), 'configurable_language');
$configurableLanguage = new ConfigurableLanguage(['direction' => ConfigurableLanguage::DIRECTION_RTL], 'configurable_language');
$this->assertEquals(ConfigurableLanguage::DIRECTION_RTL, $configurableLanguage->getDirection());
}
@ -36,7 +36,7 @@ class ConfigurableLanguageUnitTest extends UnitTestCase {
public function testWeight() {
// The weight, an integer. Used to order languages with larger positive
// weights sinking items toward the bottom of lists.
$configurableLanguage = new ConfigurableLanguage(array('weight' => -5), 'configurable_language');
$configurableLanguage = new ConfigurableLanguage(['weight' => -5], 'configurable_language');
$this->assertEquals($configurableLanguage->getWeight(), -5);
$this->assertEquals($configurableLanguage->setWeight(13)->getWeight(), 13);
}

View file

@ -86,17 +86,17 @@ class ContentLanguageSettingsUnitTest extends UnitTestCase {
$target_entity_type = $this->getMock('\Drupal\Core\Entity\EntityTypeInterface');
$target_entity_type->expects($this->any())
->method('getBundleConfigDependency')
->will($this->returnValue(array('type' => 'config', 'name' => 'test.test_entity_type.id')));
->will($this->returnValue(['type' => 'config', 'name' => 'test.test_entity_type.id']));
$this->entityManager->expects($this->any())
->method('getDefinition')
->with('test_entity_type')
->will($this->returnValue($target_entity_type));
$config = new ContentLanguageSettings(array(
$config = new ContentLanguageSettings([
'target_entity_type_id' => 'test_entity_type',
'target_bundle' => 'test_bundle',
), 'language_content_settings');
], 'language_content_settings');
$dependencies = $config->calculateDependencies()->getDependencies();
$this->assertContains('test.test_entity_type.id', $dependencies['config']);
}
@ -105,10 +105,10 @@ class ContentLanguageSettingsUnitTest extends UnitTestCase {
* @covers ::id
*/
public function testId() {
$config = new ContentLanguageSettings(array(
$config = new ContentLanguageSettings([
'target_entity_type_id' => 'test_entity_type',
'target_bundle' => 'test_bundle',
), 'language_content_settings');
], 'language_content_settings');
$this->assertSame('test_entity_type.test_bundle', $config->id());
}
@ -116,10 +116,10 @@ class ContentLanguageSettingsUnitTest extends UnitTestCase {
* @covers ::getTargetEntityTypeId
*/
public function testTargetEntityTypeId() {
$config = new ContentLanguageSettings(array(
$config = new ContentLanguageSettings([
'target_entity_type_id' => 'test_entity_type',
'target_bundle' => 'test_bundle',
), 'language_content_settings');
], 'language_content_settings');
$this->assertSame('test_entity_type', $config->getTargetEntityTypeId());
}
@ -127,10 +127,10 @@ class ContentLanguageSettingsUnitTest extends UnitTestCase {
* @covers ::getTargetBundle
*/
public function testTargetBundle() {
$config = new ContentLanguageSettings(array(
$config = new ContentLanguageSettings([
'target_entity_type_id' => 'test_entity_type',
'target_bundle' => 'test_bundle',
), 'language_content_settings');
], 'language_content_settings');
$this->assertSame('test_bundle', $config->getTargetBundle());
}
@ -146,16 +146,16 @@ class ContentLanguageSettingsUnitTest extends UnitTestCase {
public function providerDefaultLangcode() {
$langcode = $this->randomMachineName();
$config = new ContentLanguageSettings(array(
$config = new ContentLanguageSettings([
'target_entity_type_id' => 'test_entity_type',
'target_bundle' => 'test_bundle',
), 'language_content_settings');
], 'language_content_settings');
$config->setDefaultLangcode($langcode);
$defaultConfig = new ContentLanguageSettings(array(
$defaultConfig = new ContentLanguageSettings([
'target_entity_type_id' => 'test_entity_type',
'target_bundle' => 'test_default_language_bundle',
), 'language_content_settings');
], 'language_content_settings');
return [
[$config, $langcode],
@ -174,22 +174,22 @@ class ContentLanguageSettingsUnitTest extends UnitTestCase {
}
public function providerLanguageAlterable() {
$alterableConfig = new ContentLanguageSettings(array(
$alterableConfig = new ContentLanguageSettings([
'target_entity_type_id' => 'test_entity_type',
'target_bundle' => 'test_bundle',
), 'language_content_settings');
], 'language_content_settings');
$alterableConfig->setLanguageAlterable(TRUE);
$nonAlterableConfig = new ContentLanguageSettings(array(
$nonAlterableConfig = new ContentLanguageSettings([
'target_entity_type_id' => 'test_entity_type',
'target_bundle' => 'test_fixed_language_bundle',
), 'language_content_settings');
], 'language_content_settings');
$nonAlterableConfig->setLanguageAlterable(FALSE);
$defaultConfig = new ContentLanguageSettings(array(
$defaultConfig = new ContentLanguageSettings([
'target_entity_type_id' => 'test_entity_type',
'target_bundle' => 'test_default_language_bundle',
), 'language_content_settings');
], 'language_content_settings');
return [
[$alterableConfig, TRUE],
@ -208,22 +208,22 @@ class ContentLanguageSettingsUnitTest extends UnitTestCase {
}
public function providerIsDefaultConfiguration() {
$alteredLanguage = new ContentLanguageSettings(array(
$alteredLanguage = new ContentLanguageSettings([
'target_entity_type_id' => 'test_entity_type',
'target_bundle' => 'test_bundle',
), 'language_content_settings');
], 'language_content_settings');
$alteredLanguage->setLanguageAlterable(TRUE);
$alteredDefaultLangcode = new ContentLanguageSettings(array(
$alteredDefaultLangcode = new ContentLanguageSettings([
'target_entity_type_id' => 'test_entity_type',
'target_bundle' => 'test_fixed_language_bundle',
), 'language_content_settings');
], 'language_content_settings');
$alteredDefaultLangcode->setDefaultLangcode($this->randomMachineName());
$defaultConfig = new ContentLanguageSettings(array(
$defaultConfig = new ContentLanguageSettings([
'target_entity_type_id' => 'test_entity_type',
'target_bundle' => 'test_default_language_bundle',
), 'language_content_settings');
], 'language_content_settings');
return [
[$alteredLanguage, FALSE],
@ -240,10 +240,10 @@ class ContentLanguageSettingsUnitTest extends UnitTestCase {
public function testLoadByEntityTypeBundle($config_id, ContentLanguageSettings $existing_config = NULL, $expected_langcode, $expected_language_alterable) {
list($type, $bundle) = explode('.', $config_id);
$nullConfig = new ContentLanguageSettings(array(
$nullConfig = new ContentLanguageSettings([
'target_entity_type_id' => $type,
'target_bundle' => $bundle,
), 'language_content_settings');
], 'language_content_settings');
$this->configEntityStorageInterface
->expects($this->any())
->method('load')
@ -271,23 +271,23 @@ class ContentLanguageSettingsUnitTest extends UnitTestCase {
}
public function providerLoadByEntityTypeBundle() {
$alteredLanguage = new ContentLanguageSettings(array(
$alteredLanguage = new ContentLanguageSettings([
'target_entity_type_id' => 'test_entity_type',
'target_bundle' => 'test_bundle',
), 'language_content_settings');
], 'language_content_settings');
$alteredLanguage->setLanguageAlterable(TRUE);
$langcode = $this->randomMachineName();
$alteredDefaultLangcode = new ContentLanguageSettings(array(
$alteredDefaultLangcode = new ContentLanguageSettings([
'target_entity_type_id' => 'test_entity_type',
'target_bundle' => 'test_fixed_language_bundle',
), 'language_content_settings');
], 'language_content_settings');
$alteredDefaultLangcode->setDefaultLangcode($langcode);
$defaultConfig = new ContentLanguageSettings(array(
$defaultConfig = new ContentLanguageSettings([
'target_entity_type_id' => 'test_entity_type',
'target_bundle' => 'test_default_language_bundle',
), 'language_content_settings');
], 'language_content_settings');
return [
['test_entity_type.test_bundle', $alteredLanguage, LanguageInterface::LANGCODE_SITE_DEFAULT, TRUE],

View file

@ -33,10 +33,10 @@ class LanguageNegotiationUrlTest extends UnitTestCase {
$language_en->expects($this->any())
->method('getId')
->will($this->returnValue('en'));
$languages = array(
$languages = [
'de' => $language_de,
'en' => $language_en,
);
];
$this->languages = $languages;
// Create a language manager stub.
@ -126,7 +126,7 @@ class LanguageNegotiationUrlTest extends UnitTestCase {
// No configuration.
$path_prefix_configuration[] = [
'prefix' => 'de',
'prefixes' => array(),
'prefixes' => [],
'expected_langcode' => FALSE,
];
// Non-matching prefix.
@ -168,7 +168,7 @@ class LanguageNegotiationUrlTest extends UnitTestCase {
],
]);
$request = Request::create('', 'GET', array(), array(), array(), array('HTTP_HOST' => $http_host));
$request = Request::create('', 'GET', [], [], [], ['HTTP_HOST' => $http_host]);
$method = new LanguageNegotiationUrl();
$method->setLanguageManager($this->languageManager);
$method->setConfig($config);
@ -193,60 +193,60 @@ class LanguageNegotiationUrlTest extends UnitTestCase {
*/
public function providerTestDomain() {
$domain_configuration[] = array(
$domain_configuration[] = [
'http_host' => 'example.de',
'domains' => array(
'domains' => [
'de' => 'http://example.de',
),
],
'expected_langcode' => 'de',
);
];
// No configuration.
$domain_configuration[] = array(
$domain_configuration[] = [
'http_host' => 'example.de',
'domains' => array(),
'domains' => [],
'expected_langcode' => FALSE,
);
];
// HTTP host with a port.
$domain_configuration[] = array(
$domain_configuration[] = [
'http_host' => 'example.de:8080',
'domains' => array(
'domains' => [
'de' => 'http://example.de',
),
],
'expected_langcode' => 'de',
);
];
// Domain configuration with https://.
$domain_configuration[] = array(
$domain_configuration[] = [
'http_host' => 'example.de',
'domains' => array(
'domains' => [
'de' => 'https://example.de',
),
],
'expected_langcode' => 'de',
);
];
// Non-matching HTTP host.
$domain_configuration[] = array(
$domain_configuration[] = [
'http_host' => 'example.com',
'domains' => array(
'domains' => [
'de' => 'http://example.com',
),
],
'expected_langcode' => 'de',
);
];
// Testing a non-existing language.
$domain_configuration[] = array(
$domain_configuration[] = [
'http_host' => 'example.com',
'domains' => array(
'domains' => [
'it' => 'http://example.it',
),
],
'expected_langcode' => FALSE,
);
];
// Multiple domain configurations.
$domain_configuration[] = array(
$domain_configuration[] = [
'http_host' => 'example.com',
'domains' => array(
'domains' => [
'de' => 'http://example.de',
'en' => 'http://example.com',
),
],
'expected_langcode' => 'en',
);
];
return $domain_configuration;
}

View file

@ -12,9 +12,9 @@ use Drupal\Tests\Core\Menu\LocalTaskIntegrationTestBase;
class LanguageLocalTasksTest extends LocalTaskIntegrationTestBase {
protected function setUp() {
$this->directoryList = array(
$this->directoryList = [
'language' => 'core/modules/language',
);
];
parent::setUp();
}
@ -31,19 +31,19 @@ class LanguageLocalTasksTest extends LocalTaskIntegrationTestBase {
* Provides a list of routes to test.
*/
public function getLanguageAdminOverviewRoutes() {
return array(
array('entity.configurable_language.collection', array(array('entity.configurable_language.collection', 'language.negotiation'))),
array('language.negotiation', array(array('entity.configurable_language.collection', 'language.negotiation'))),
);
return [
['entity.configurable_language.collection', [['entity.configurable_language.collection', 'language.negotiation']]],
['language.negotiation', [['entity.configurable_language.collection', 'language.negotiation']]],
];
}
/**
* Tests language edit local tasks existence.
*/
public function testLanguageEditLocalTasks() {
$this->assertLocalTasks('entity.configurable_language.edit_form', array(
0 => array('entity.configurable_language.edit_form'),
));
$this->assertLocalTasks('entity.configurable_language.edit_form', [
0 => ['entity.configurable_language.edit_form'],
]);
}
}

View file

@ -1,83 +0,0 @@
<?php
namespace Drupal\Tests\language\Unit\Migrate;
use Drupal\language\Plugin\migrate\source\Language;
use Drupal\Tests\migrate\Unit\MigrateSqlSourceTestCase;
/**
* @coversDefaultClass \Drupal\language\Plugin\migrate\source\Language
* @group language
*/
class LanguageTest extends MigrateSqlSourceTestCase {
const PLUGIN_CLASS = Language::class;
protected $migrationConfiguration = array(
'id' => 'test',
'source' => array(
'plugin' => 'language',
),
);
protected $databaseContents = array(
'languages' => array(
array(
'language' => 'en',
'name' => 'English',
'native' => 'English',
'direction' => '0',
'enabled' => '1',
'plurals' => '0',
'formula' => '',
'domain' => '',
'prefix' => '',
'weight' => '0',
'javascript' => '',
),
array(
'language' => 'fr',
'name' => 'French',
'native' => 'Français',
'direction' => '0',
'enabled' => '0',
'plurals' => '2',
'formula' => '($n>1)',
'domain' => '',
'prefix' => 'fr',
'weight' => '0',
'javascript' => '',
),
),
);
protected $expectedResults = array(
array(
'language' => 'en',
'name' => 'English',
'native' => 'English',
'direction' => '0',
'enabled' => '1',
'plurals' => '0',
'formula' => '',
'domain' => '',
'prefix' => '',
'weight' => '0',
'javascript' => '',
),
array(
'language' => 'fr',
'name' => 'French',
'native' => 'Français',
'direction' => '0',
'enabled' => '0',
'plurals' => '2',
'formula' => '($n>1)',
'domain' => '',
'prefix' => 'fr',
'weight' => '0',
'javascript' => '',
),
);
}

View file

@ -4,6 +4,7 @@ namespace Drupal\Tests\language\Unit\process;
use Drupal\language\Plugin\migrate\process\LanguageNegotiation;
use Drupal\Tests\migrate\Unit\process\MigrateProcessTestCase;
use Drupal\migrate\MigrateException;
/**
* @coversDefaultClass \Drupal\language\Plugin\migrate\process\LanguageNegotiation
@ -75,12 +76,10 @@ class LanguageNegotiationTest extends MigrateProcessTestCase {
/**
* Tests string input.
*
* @expectedException \Drupal\migrate\MigrateException
* @expectedExceptionMessage The input should be an array
*/
public function testStringInput() {
$this->plugin = new LanguageNegotiation([], 'map', []);
$this->setExpectedException(MigrateException::class, 'The input should be an array');
$this->plugin->transform('foo', $this->migrateExecutable, $this->row, 'destinationproperty');
}

View file

@ -4,6 +4,7 @@ namespace Drupal\Tests\language\Unit\process;
use Drupal\language\Plugin\migrate\process\LanguageTypes;
use Drupal\Tests\migrate\Unit\process\MigrateProcessTestCase;
use Drupal\migrate\MigrateException;
/**
* @coversDefaultClass \Drupal\language\Plugin\migrate\process\LanguageTypes
@ -49,12 +50,10 @@ class LanguageTypesTest extends MigrateProcessTestCase {
/**
* Tests string input.
*
* @expectedException \Drupal\migrate\MigrateException
* @expectedExceptionMessage The input should be an array
*/
public function testStringInput() {
$this->plugin = new LanguageTypes([], 'map', []);
$this->setExpectedException(MigrateException::class, 'The input should be an array');
$this->plugin->transform('foo', $this->migrateExecutable, $this->row, 'destinationproperty');
}