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

@ -42,10 +42,10 @@ class LocaleController extends ControllerBase {
* The render array for the string search screen.
*/
public function translatePage() {
return array(
return [
'filter' => $this->formBuilder()->getForm('Drupal\locale\Form\TranslateFilterForm'),
'form' => $this->formBuilder()->getForm('Drupal\locale\Form\TranslateEditForm'),
);
];
}
}

View file

@ -66,7 +66,7 @@ class ExportForm extends FormBase {
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$languages = $this->languageManager->getLanguages();
$language_options = array();
$language_options = [];
foreach ($languages as $langcode => $language) {
if (locale_is_translatable($langcode)) {
$language_options[$langcode] = $language->getName();
@ -75,60 +75,59 @@ class ExportForm extends FormBase {
$language_default = $this->languageManager->getDefaultLanguage();
if (empty($language_options)) {
$form['langcode'] = array(
$form['langcode'] = [
'#type' => 'value',
'#value' => LanguageInterface::LANGCODE_SYSTEM,
);
$form['langcode_text'] = array(
];
$form['langcode_text'] = [
'#type' => 'item',
'#title' => $this->t('Language'),
'#markup' => $this->t('No language available. The export will only contain source strings.'),
);
];
}
else {
$form['langcode'] = array(
$form['langcode'] = [
'#type' => 'select',
'#title' => $this->t('Language'),
'#options' => $language_options,
'#default_value' => $language_default->getId(),
'#empty_option' => $this->t('Source text only, no translations'),
'#empty_value' => LanguageInterface::LANGCODE_SYSTEM,
);
$form['content_options'] = array(
];
$form['content_options'] = [
'#type' => 'details',
'#title' => $this->t('Export options'),
'#collapsed' => TRUE,
'#tree' => TRUE,
'#states' => array(
'invisible' => array(
':input[name="langcode"]' => array('value' => LanguageInterface::LANGCODE_SYSTEM),
),
),
);
$form['content_options']['not_customized'] = array(
'#states' => [
'invisible' => [
':input[name="langcode"]' => ['value' => LanguageInterface::LANGCODE_SYSTEM],
],
],
];
$form['content_options']['not_customized'] = [
'#type' => 'checkbox',
'#title' => $this->t('Include non-customized translations'),
'#default_value' => TRUE,
);
$form['content_options']['customized'] = array(
];
$form['content_options']['customized'] = [
'#type' => 'checkbox',
'#title' => $this->t('Include customized translations'),
'#default_value' => TRUE,
);
$form['content_options']['not_translated'] = array(
];
$form['content_options']['not_translated'] = [
'#type' => 'checkbox',
'#title' => $this->t('Include untranslated text'),
'#default_value' => TRUE,
);
];
}
$form['actions'] = array(
$form['actions'] = [
'#type' => 'actions',
);
$form['actions']['submit'] = array(
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Export'),
);
];
return $form;
}
@ -143,7 +142,7 @@ class ExportForm extends FormBase {
else {
$language = NULL;
}
$content_options = $form_state->getValue('content_options', array());
$content_options = $form_state->getValue('content_options', []);
$reader = new PoDatabaseReader();
$language_name = '';
if ($language != NULL) {

View file

@ -72,7 +72,7 @@ class ImportForm extends FormBase {
// Initialize a language list to the ones available, including English if we
// are to translate Drupal to English as well.
$existing_languages = array();
$existing_languages = [];
foreach ($languages as $langcode => $language) {
if (locale_is_translatable($langcode)) {
$existing_languages[$langcode] = $language->getName();
@ -88,65 +88,65 @@ class ImportForm extends FormBase {
}
else {
$default = key($existing_languages);
$language_options = array(
$language_options = [
(string) $this->t('Existing languages') => $existing_languages,
(string) $this->t('Languages not yet added') => $this->languageManager->getStandardLanguageListWithoutConfigured(),
);
];
}
$validators = array(
'file_validate_extensions' => array('po'),
'file_validate_size' => array(file_upload_max_size()),
);
$form['file'] = array(
$validators = [
'file_validate_extensions' => ['po'],
'file_validate_size' => [file_upload_max_size()],
];
$form['file'] = [
'#type' => 'file',
'#title' => $this->t('Translation file'),
'#description' => array(
'#description' => [
'#theme' => 'file_upload_help',
'#description' => $this->t('A Gettext Portable Object file.'),
'#upload_validators' => $validators,
),
],
'#size' => 50,
'#upload_validators' => $validators,
'#attributes' => array('class' => array('file-import-input')),
);
$form['langcode'] = array(
'#attributes' => ['class' => ['file-import-input']],
];
$form['langcode'] = [
'#type' => 'select',
'#title' => $this->t('Language'),
'#options' => $language_options,
'#default_value' => $default,
'#attributes' => array('class' => array('langcode-input')),
);
'#attributes' => ['class' => ['langcode-input']],
];
$form['customized'] = array(
$form['customized'] = [
'#title' => $this->t('Treat imported strings as custom translations'),
'#type' => 'checkbox',
);
$form['overwrite_options'] = array(
];
$form['overwrite_options'] = [
'#type' => 'container',
'#tree' => TRUE,
);
$form['overwrite_options']['not_customized'] = array(
];
$form['overwrite_options']['not_customized'] = [
'#title' => $this->t('Overwrite non-customized translations'),
'#type' => 'checkbox',
'#states' => array(
'checked' => array(
':input[name="customized"]' => array('checked' => TRUE),
),
),
);
$form['overwrite_options']['customized'] = array(
'#states' => [
'checked' => [
':input[name="customized"]' => ['checked' => TRUE],
],
],
];
$form['overwrite_options']['customized'] = [
'#title' => $this->t('Overwrite existing customized translations'),
'#type' => 'checkbox',
);
];
$form['actions'] = array(
$form['actions'] = [
'#type' => 'actions',
);
$form['actions']['submit'] = array(
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Import'),
);
];
return $form;
}
@ -172,21 +172,21 @@ class ImportForm extends FormBase {
if (empty($language)) {
$language = ConfigurableLanguage::createFromLangcode($form_state->getValue('langcode'));
$language->save();
drupal_set_message($this->t('The language %language has been created.', array('%language' => $this->t($language->label()))));
drupal_set_message($this->t('The language %language has been created.', ['%language' => $this->t($language->label())]));
}
$options = array_merge(_locale_translation_default_update_options(), array(
$options = array_merge(_locale_translation_default_update_options(), [
'langcode' => $form_state->getValue('langcode'),
'overwrite_options' => $form_state->getValue('overwrite_options'),
'customized' => $form_state->getValue('customized') ? LOCALE_CUSTOMIZED : LOCALE_NOT_CUSTOMIZED,
));
]);
$this->moduleHandler->loadInclude('locale', 'bulk.inc');
$file = locale_translate_file_attach_properties($this->file, $options);
$batch = locale_translate_batch_build(array($file->uri => $file), $options);
$batch = locale_translate_batch_build([$file->uri => $file], $options);
batch_set($batch);
// Create or update all configuration translations for this language.
\Drupal::moduleHandler()->loadInclude('locale', 'bulk.inc');
if ($batch = locale_config_batch_update_components($options, array($form_state->getValue('langcode')))) {
if ($batch = locale_config_batch_update_components($options, [$form_state->getValue('langcode')])) {
batch_set($batch);
}

View file

@ -30,35 +30,35 @@ class LocaleSettingsForm extends ConfigFormBase {
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('locale.settings');
$form['update_interval_days'] = array(
$form['update_interval_days'] = [
'#type' => 'radios',
'#title' => $this->t('Check for updates'),
'#default_value' => $config->get('translation.update_interval_days'),
'#options' => array(
'#options' => [
'0' => $this->t('Never (manually)'),
'7' => $this->t('Weekly'),
'30' => $this->t('Monthly'),
),
'#description' => $this->t('Select how frequently you want to check for new interface translations for your currently installed modules and themes. <a href=":url">Check updates now</a>.', array(':url' => $this->url('locale.check_translation'))),
);
],
'#description' => $this->t('Select how frequently you want to check for new interface translations for your currently installed modules and themes. <a href=":url">Check updates now</a>.', [':url' => $this->url('locale.check_translation')]),
];
if ($directory = $config->get('translation.path')) {
$description = $this->t('Translation files are stored locally in the %path directory. You can change this directory on the <a href=":url">File system</a> configuration page.', array('%path' => $directory, ':url' => $this->url('system.file_system_settings')));
$description = $this->t('Translation files are stored locally in the %path directory. You can change this directory on the <a href=":url">File system</a> configuration page.', ['%path' => $directory, ':url' => $this->url('system.file_system_settings')]);
}
else {
$description = $this->t('Translation files will not be stored locally. Change the Interface translation directory on the <a href=":url">File system configuration</a> page.', array(':url' => $this->url('system.file_system_settings')));
$description = $this->t('Translation files will not be stored locally. Change the Interface translation directory on the <a href=":url">File system configuration</a> page.', [':url' => $this->url('system.file_system_settings')]);
}
$form['#translation_directory'] = $directory;
$form['use_source'] = array(
$form['use_source'] = [
'#type' => 'radios',
'#title' => $this->t('Translation source'),
'#default_value' => $config->get('translation.use_source'),
'#options' => array(
'#options' => [
LOCALE_TRANSLATION_USE_SOURCE_REMOTE_AND_LOCAL => $this->t('Drupal translation server and local files'),
LOCALE_TRANSLATION_USE_SOURCE_LOCAL => $this->t('Local files only'),
),
],
'#description' => $this->t('The source of translation files for automatic interface translation.') . ' ' . $description,
);
];
if ($config->get('translation.overwrite_not_customized') == FALSE) {
$default = LOCALE_TRANSLATION_OVERWRITE_NONE;
@ -69,17 +69,17 @@ class LocaleSettingsForm extends ConfigFormBase {
else {
$default = LOCALE_TRANSLATION_OVERWRITE_NON_CUSTOMIZED;
}
$form['overwrite'] = array(
$form['overwrite'] = [
'#type' => 'radios',
'#title' => $this->t('Import behavior'),
'#default_value' => $default,
'#options' => array(
'#options' => [
LOCALE_TRANSLATION_OVERWRITE_NONE => $this->t("Don't overwrite existing translations."),
LOCALE_TRANSLATION_OVERWRITE_NON_CUSTOMIZED => $this->t('Only overwrite imported translations, customized translations are kept.'),
LOCALE_TRANSLATION_OVERWRITE_ALL => $this->t('Overwrite existing translations.'),
),
],
'#description' => $this->t('How to treat existing translations when automatically updating the interface translations.'),
);
];
return parent::buildForm($form, $form_state);
}
@ -91,7 +91,7 @@ class LocaleSettingsForm extends ConfigFormBase {
parent::validateForm($form, $form_state);
if (empty($form['#translation_directory']) && $form_state->getValue('use_source') == LOCALE_TRANSLATION_USE_SOURCE_LOCAL) {
$form_state->setErrorByName('use_source', $this->t('You have selected local translation source, but no <a href=":url">Interface translation directory</a> was configured.', array(':url' => $this->url('system.file_system_settings'))));
$form_state->setErrorByName('use_source', $this->t('You have selected local translation source, but no <a href=":url">Interface translation directory</a> was configured.', [':url' => $this->url('system.file_system_settings')]));
}
}

View file

@ -32,12 +32,12 @@ class TranslateEditForm extends TranslateFormBase {
$form['#attached']['library'][] = 'locale/drupal.locale.admin';
$form['langcode'] = array(
$form['langcode'] = [
'#type' => 'value',
'#value' => $filter_values['langcode'],
);
];
$form['strings'] = array(
$form['strings'] = [
'#type' => 'table',
'#tree' => TRUE,
'#language' => $langname,
@ -47,7 +47,7 @@ class TranslateEditForm extends TranslateFormBase {
],
'#empty' => $this->t('No strings available.'),
'#attributes' => ['class' => ['locale-translate-edit-table']],
);
];
if (isset($langcode)) {
$strings = $this->translateFilterLoadStrings();
@ -63,14 +63,14 @@ class TranslateEditForm extends TranslateFormBase {
if (count($source_array) == 1) {
// Add original string value and mark as non-plural.
$plural = FALSE;
$form['strings'][$string->lid]['original'] = array(
$form['strings'][$string->lid]['original'] = [
'#type' => 'item',
'#title' => $this->t('Source string (@language)', array('@language' => $this->t('Built-in English'))),
'#title' => $this->t('Source string (@language)', ['@language' => $this->t('Built-in English')]),
'#title_display' => 'invisible',
'#plain_text' => $source_array[0],
'#preffix' => '<span lang="en">',
'#suffix' => '</span>',
);
];
}
else {
// Add original string value and mark as plural.
@ -79,7 +79,7 @@ class TranslateEditForm extends TranslateFormBase {
'#type' => 'item',
'#title' => $this->t('Singular form'),
'#plain_text' => $source_array[0],
'#prefix' => '<span class="visually-hidden">' . $this->t('Source string (@language)', array('@language' => $this->t('Built-in English'))) . '</span><span lang="en">',
'#prefix' => '<span class="visually-hidden">' . $this->t('Source string (@language)', ['@language' => $this->t('Built-in English')]) . '</span><span lang="en">',
'#suffix' => '</span>',
];
$original_plural = [
@ -108,27 +108,27 @@ class TranslateEditForm extends TranslateFormBase {
// Approximate the number of rows to use in the default textarea.
$rows = min(ceil(str_word_count($source_array[0]) / 12), 10);
if (!$plural) {
$form['strings'][$string->lid]['translations'][0] = array(
$form['strings'][$string->lid]['translations'][0] = [
'#type' => 'textarea',
'#title' => $this->t('Translated string (@language)', array('@language' => $langname)),
'#title' => $this->t('Translated string (@language)', ['@language' => $langname]),
'#title_display' => 'invisible',
'#rows' => $rows,
'#default_value' => $translation_array[0],
'#attributes' => array('lang' => $langcode),
);
'#attributes' => ['lang' => $langcode],
];
}
else {
// Add a textarea for each plural variant.
for ($i = 0; $i < $plurals; $i++) {
$form['strings'][$string->lid]['translations'][$i] = array(
$form['strings'][$string->lid]['translations'][$i] = [
'#type' => 'textarea',
// @todo Should use better labels https://www.drupal.org/node/2499639
'#title' => ($i == 0 ? $this->t('Singular form') : $this->formatPlural($i, 'First plural form', '@count. plural form')),
'#rows' => $rows,
'#default_value' => isset($translation_array[$i]) ? $translation_array[$i] : '',
'#attributes' => array('lang' => $langcode),
'#prefix' => $i == 0 ? ('<span class="visually-hidden">' . $this->t('Translated string (@language)', array('@language' => $langname)) . '</span>') : '',
);
'#attributes' => ['lang' => $langcode],
'#prefix' => $i == 0 ? ('<span class="visually-hidden">' . $this->t('Translated string (@language)', ['@language' => $langname]) . '</span>') : '',
];
}
if ($plurals == 2) {
// Simplify interface text for the most common case.
@ -137,11 +137,11 @@ class TranslateEditForm extends TranslateFormBase {
}
}
if (count(Element::children($form['strings']))) {
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
$form['actions'] = ['#type' => 'actions'];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Save translations'),
);
];
}
}
$form['pager']['#type'] = 'pager';
@ -156,9 +156,9 @@ class TranslateEditForm extends TranslateFormBase {
foreach ($form_state->getValue('strings') as $lid => $translations) {
foreach ($translations['translations'] as $key => $value) {
if (!locale_string_is_safe($value)) {
$form_state->setErrorByName("strings][$lid][translations][$key", $this->t('The submitted string contains disallowed HTML: %string', array('%string' => $value)));
$form_state->setErrorByName("translations][$langcode][$key", $this->t('The submitted string contains disallowed HTML: %string', array('%string' => $value)));
$this->logger('locale')->warning('Attempted submission of a translation string with disallowed HTML: %string', array('%string' => $value));
$form_state->setErrorByName("strings][$lid][translations][$key", $this->t('The submitted string contains disallowed HTML: %string', ['%string' => $value]));
$form_state->setErrorByName("translations][$langcode][$key", $this->t('The submitted string contains disallowed HTML: %string', ['%string' => $value]));
$this->logger('locale')->warning('Attempted submission of a translation string with disallowed HTML: %string', ['%string' => $value]);
}
}
}
@ -169,12 +169,12 @@ class TranslateEditForm extends TranslateFormBase {
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$langcode = $form_state->getValue('langcode');
$updated = array();
$updated = [];
// Preload all translations for strings in the form.
$lids = array_keys($form_state->getValue('strings'));
$existing_translation_objects = array();
foreach ($this->localeStorage->getTranslations(array('lid' => $lids, 'language' => $langcode, 'translated' => TRUE)) as $existing_translation_object) {
$existing_translation_objects = [];
foreach ($this->localeStorage->getTranslations(['lid' => $lids, 'language' => $langcode, 'translated' => TRUE]) as $existing_translation_object) {
$existing_translation_objects[$existing_translation_object->lid] = $existing_translation_object;
}
@ -204,7 +204,7 @@ class TranslateEditForm extends TranslateFormBase {
if ($is_changed) {
// Only update or insert if we have a value to use.
$target = isset($existing_translation_objects[$lid]) ? $existing_translation_objects[$lid] : $this->localeStorage->createTranslation(array('lid' => $lid, 'language' => $langcode));
$target = isset($existing_translation_objects[$lid]) ? $existing_translation_objects[$lid] : $this->localeStorage->createTranslation(['lid' => $lid, 'language' => $langcode]);
$target->setPlurals($new_translation['translations'])
->setCustomized()
->save();
@ -224,15 +224,15 @@ class TranslateEditForm extends TranslateFormBase {
if (isset($page)) {
$form_state->setRedirect(
'locale.translate_page',
array(),
array('page' => $page)
[],
['page' => $page]
);
}
if ($updated) {
// Clear cache and force refresh of JavaScript translations.
_locale_refresh_translations(array($langcode), $updated);
_locale_refresh_configuration(array($langcode), $updated);
_locale_refresh_translations([$langcode], $updated);
_locale_refresh_configuration([$langcode], $updated);
}
}

View file

@ -25,24 +25,24 @@ class TranslateFilterForm extends TranslateFormBase {
$form['#attached']['library'][] = 'locale/drupal.locale.admin';
$form['filters'] = array(
$form['filters'] = [
'#type' => 'details',
'#title' => $this->t('Filter translatable strings'),
'#open' => TRUE,
);
];
foreach ($filters as $key => $filter) {
// Special case for 'string' filter.
if ($key == 'string') {
$form['filters']['status']['string'] = array(
$form['filters']['status']['string'] = [
'#type' => 'search',
'#title' => $filter['title'],
'#description' => $filter['description'],
'#default_value' => $filter_values[$key],
);
];
}
else {
$empty_option = isset($filter['options'][$filter['default']]) ? $filter['options'][$filter['default']] : '- None -';
$form['filters']['status'][$key] = array(
$form['filters']['status'][$key] = [
'#title' => $filter['title'],
'#type' => 'select',
'#empty_value' => $filter['default'],
@ -50,27 +50,27 @@ class TranslateFilterForm extends TranslateFormBase {
'#size' => 0,
'#options' => $filter['options'],
'#default_value' => $filter_values[$key],
);
];
if (isset($filter['states'])) {
$form['filters']['status'][$key]['#states'] = $filter['states'];
}
}
}
$form['filters']['actions'] = array(
$form['filters']['actions'] = [
'#type' => 'actions',
'#attributes' => array('class' => array('container-inline')),
);
$form['filters']['actions']['submit'] = array(
'#attributes' => ['class' => ['container-inline']],
];
$form['filters']['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Filter'),
);
];
if (!empty($_SESSION['locale_translate_filter'])) {
$form['filters']['actions']['reset'] = array(
$form['filters']['actions']['reset'] = [
'#type' => 'submit',
'#value' => $this->t('Reset'),
'#submit' => array('::resetForm'),
);
'#submit' => ['::resetForm'],
];
}
return $form;
@ -93,7 +93,7 @@ class TranslateFilterForm extends TranslateFormBase {
* Provides a submit handler for the reset button.
*/
public function resetForm(array &$form, FormStateInterface $form_state) {
$_SESSION['locale_translate_filter'] = array();
$_SESSION['locale_translate_filter'] = [];
$form_state->setRedirect('locale.translate_page');
}

View file

@ -81,8 +81,8 @@ abstract class TranslateFormBase extends FormBase {
// Language is sanitized to be one of the possible options in
// translateFilterValues().
$conditions = array('language' => $filter_values['langcode']);
$options = array('pager limit' => 30, 'translated' => TRUE, 'untranslated' => TRUE);
$conditions = ['language' => $filter_values['langcode']];
$options = ['pager limit' => 30, 'translated' => TRUE, 'untranslated' => TRUE];
// Add translation status conditions and options.
switch ($filter_values['translation']) {
@ -123,7 +123,7 @@ abstract class TranslateFormBase extends FormBase {
return static::$filterValues;
}
$filter_values = array();
$filter_values = [];
$filters = $this->translateFilters();
foreach ($filters as $key => $filter) {
$filter_values[$key] = $filter['default'];
@ -152,12 +152,12 @@ abstract class TranslateFormBase extends FormBase {
* Lists locale translation filters that can be applied.
*/
protected function translateFilters() {
$filters = array();
$filters = [];
// Get all languages, except English.
$this->languageManager->reset();
$languages = $this->languageManager->getLanguages();
$language_options = array();
$language_options = [];
foreach ($languages as $langcode => $language) {
if (locale_is_translatable($langcode)) {
$language_options[$langcode] = $language->getName();
@ -171,42 +171,42 @@ abstract class TranslateFormBase extends FormBase {
$default_langcode = array_shift($available_langcodes);
}
$filters['string'] = array(
$filters['string'] = [
'title' => $this->t('String contains'),
'description' => $this->t('Leave blank to show all strings. The search is case sensitive.'),
'default' => '',
);
];
$filters['langcode'] = array(
$filters['langcode'] = [
'title' => $this->t('Translation language'),
'options' => $language_options,
'default' => $default_langcode,
);
];
$filters['translation'] = array(
$filters['translation'] = [
'title' => $this->t('Search in'),
'options' => array(
'options' => [
'all' => $this->t('Both translated and untranslated strings'),
'translated' => $this->t('Only translated strings'),
'untranslated' => $this->t('Only untranslated strings'),
),
],
'default' => 'all',
);
];
$filters['customized'] = array(
$filters['customized'] = [
'title' => $this->t('Translation type'),
'options' => array(
'options' => [
'all' => $this->t('All'),
LOCALE_NOT_CUSTOMIZED => $this->t('Non-customized translation'),
LOCALE_CUSTOMIZED => $this->t('Customized translation'),
),
'states' => array(
'visible' => array(
':input[name=translation]' => array('value' => 'translated'),
),
),
],
'states' => [
'visible' => [
':input[name=translation]' => ['value' => 'translated'],
],
],
'default' => 'all',
);
];
return $filters;
}

View file

@ -65,10 +65,10 @@ class TranslationStatusForm extends FormBase {
public function buildForm(array $form, FormStateInterface $form_state) {
$languages = locale_translatable_language_list();
$status = locale_translation_get_status();
$options = array();
$languages_update = array();
$languages_not_found = array();
$projects_update = array();
$options = [];
$languages_update = [];
$languages_not_found = [];
$projects_update = [];
// Prepare information about projects which have available translation
// updates.
if ($languages && $status) {
@ -77,24 +77,24 @@ class TranslationStatusForm extends FormBase {
// Build data options for the select table.
foreach ($updates as $langcode => $update) {
$title = $languages[$langcode]->getName();
$locale_translation_update_info = array('#theme' => 'locale_translation_update_info');
foreach (array('updates', 'not_found') as $update_status) {
$locale_translation_update_info = ['#theme' => 'locale_translation_update_info'];
foreach (['updates', 'not_found'] as $update_status) {
if (isset($update[$update_status])) {
$locale_translation_update_info['#' . $update_status] = $update[$update_status];
}
}
$options[$langcode] = array(
'title' => array(
'data' => array(
$options[$langcode] = [
'title' => [
'data' => [
'#title' => $title,
'#plain_text' => $title,
),
),
'status' => array(
'class' => array('description', 'priority-low'),
],
],
'status' => [
'class' => ['description', 'priority-low'],
'data' => $locale_translation_update_info,
),
);
],
];
if (!empty($update['not_found'])) {
$languages_not_found[$langcode] = $langcode;
}
@ -110,43 +110,43 @@ class TranslationStatusForm extends FormBase {
}
$last_checked = $this->state->get('locale.translation_last_checked');
$form['last_checked'] = array(
$form['last_checked'] = [
'#theme' => 'locale_translation_last_check',
'#last' => $last_checked,
);
];
$header = array(
'title' => array(
$header = [
'title' => [
'data' => $this->t('Language'),
'class' => array('title'),
),
'status' => array(
'class' => ['title'],
],
'status' => [
'data' => $this->t('Status'),
'class' => array('status', 'priority-low'),
),
);
'class' => ['status', 'priority-low'],
],
];
if (!$languages) {
$empty = $this->t('No translatable languages available. <a href=":add_language">Add a language</a> first.', array(
$empty = $this->t('No translatable languages available. <a href=":add_language">Add a language</a> first.', [
':add_language' => $this->url('entity.configurable_language.collection'),
));
]);
}
elseif ($status) {
$empty = $this->t('All translations up to date.');
}
else {
$empty = $this->t('No translation status available. <a href=":check">Check manually</a>.', array(
$empty = $this->t('No translation status available. <a href=":check">Check manually</a>.', [
':check' => $this->url('locale.check_translation'),
));
]);
}
// The projects which require an update. Used by the _submit callback.
$form['projects_update'] = array(
$form['projects_update'] = [
'#type' => 'value',
'#value' => $projects_update,
);
];
$form['langcodes'] = array(
$form['langcodes'] = [
'#type' => 'tableselect',
'#header' => $header,
'#options' => $options,
@ -156,17 +156,17 @@ class TranslationStatusForm extends FormBase {
'#multiple' => TRUE,
'#required' => TRUE,
'#not_found' => $languages_not_found,
'#after_build' => array('locale_translation_language_table'),
);
'#after_build' => ['locale_translation_language_table'],
];
$form['#attached']['library'][] = 'locale/drupal.locale.admin';
$form['actions'] = array('#type' => 'actions');
$form['actions'] = ['#type' => 'actions'];
if ($languages_update) {
$form['actions']['submit'] = array(
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Update translations'),
);
];
}
return $form;
@ -183,7 +183,7 @@ class TranslationStatusForm extends FormBase {
* translation update status.
*/
protected function prepareUpdateData(array $status) {
$updates = array();
$updates = [];
// @todo Calling locale_translation_build_projects() is an expensive way to
// get a module name. In follow-up issue
@ -196,22 +196,22 @@ class TranslationStatusForm extends FormBase {
foreach ($project as $langcode => $project_info) {
// No translation file found for this project-language combination.
if (empty($project_info->type)) {
$updates[$langcode]['not_found'][] = array(
$updates[$langcode]['not_found'][] = [
'name' => $project_info->name == 'drupal' ? $this->t('Drupal core') : $project_data[$project_info->name]->info['name'],
'version' => $project_info->version,
'info' => $this->createInfoString($project_info),
);
];
}
// Translation update found for this project-language combination.
elseif ($project_info->type == LOCALE_TRANSLATION_LOCAL || $project_info->type == LOCALE_TRANSLATION_REMOTE) {
$local = isset($project_info->files[LOCALE_TRANSLATION_LOCAL]) ? $project_info->files[LOCALE_TRANSLATION_LOCAL] : NULL;
$remote = isset($project_info->files[LOCALE_TRANSLATION_REMOTE]) ? $project_info->files[LOCALE_TRANSLATION_REMOTE] : NULL;
$recent = _locale_translation_source_compare($local, $remote) == LOCALE_TRANSLATION_SOURCE_COMPARE_LT ? $remote : $local;
$updates[$langcode]['updates'][] = array(
$updates[$langcode]['updates'][] = [
'name' => $project_info->name == 'drupal' ? $this->t('Drupal core') : $project_data[$project_info->name]->info['name'],
'version' => $project_info->version,
'timestamp' => $recent->timestamp,
);
];
}
}
}
@ -238,13 +238,13 @@ class TranslationStatusForm extends FormBase {
$local_path = isset($project_info->files['local']->uri) ? $project_info->files['local']->uri : FALSE;
if (locale_translation_use_remote_source() && $remote_path && $local_path) {
return $this->t('File not found at %remote_path nor at %local_path', array(
return $this->t('File not found at %remote_path nor at %local_path', [
'%remote_path' => $remote_path,
'%local_path' => $local_path,
));
]);
}
elseif ($local_path) {
return $this->t('File not found at %local_path', array('%local_path' => $local_path));
return $this->t('File not found at %local_path', ['%local_path' => $local_path]);
}
return $this->t('Translation file location could not be determined.');
}
@ -279,7 +279,7 @@ class TranslationStatusForm extends FormBase {
$last_checked = $this->state->get('locale.translation_last_checked');
if ($last_checked < REQUEST_TIME - LOCALE_TRANSLATION_STATUS_TTL) {
locale_translation_clear_status();
$batch = locale_translation_batch_update_build(array(), $langcodes, $options);
$batch = locale_translation_batch_update_build([], $langcodes, $options);
batch_set($batch);
}
else {

View file

@ -41,12 +41,12 @@ class Gettext {
*/
public static function fileToDatabase($file, $options) {
// Add the default values to the options array.
$options += array(
'overwrite_options' => array(),
$options += [
'overwrite_options' => [],
'customized' => LOCALE_NOT_CUSTOMIZED,
'items' => -1,
'seek' => 0,
);
];
// Instantiate and initialize the stream reader for this file.
$reader = new PoStreamReader();
$reader->setLangcode($file->langcode);
@ -67,10 +67,10 @@ class Gettext {
// Initialize the database writer.
$writer = new PoDatabaseWriter();
$writer->setLangcode($file->langcode);
$writer_options = array(
$writer_options = [
'overwrite_options' => $options['overwrite_options'],
'customized' => $options['customized'],
);
];
$writer->setOptions($writer_options);
$writer->setHeader($header);

View file

@ -147,7 +147,7 @@ class LocaleConfigManager {
return $this->getTranslatableData($typed_config);
}
}
return array();
return [];
}
/**
@ -163,7 +163,7 @@ class LocaleConfigManager {
* TranslatableMarkup.
*/
protected function getTranslatableData(TypedDataInterface $element) {
$translatable = array();
$translatable = [];
if ($element instanceof TraversableTypedDataInterface) {
foreach ($element as $key => $property) {
$value = $this->getTranslatableData($property);
@ -178,11 +178,11 @@ class LocaleConfigManager {
$value = $element->getValue();
$definition = $element->getDataDefinition();
if (!empty($definition['translatable']) && $value !== '' && $value !== NULL) {
$options = array();
$options = [];
if (isset($definition['translation context'])) {
$options['context'] = $definition['translation context'];
}
return new TranslatableMarkup($value, array(), $options);
return new TranslatableMarkup($value, [], $options);
}
}
return $translatable;
@ -215,7 +215,7 @@ class LocaleConfigManager {
* @see self::getTranslatableData()
*/
protected function processTranslatableData($name, array $active, array $translatable, $langcode) {
$translated = array();
$translated = [];
foreach ($translatable as $key => $item) {
if (!isset($active[$key])) {
continue;
@ -296,10 +296,10 @@ class LocaleConfigManager {
* @return array
* Array of configuration object names.
*/
public function getComponentNames(array $components = array()) {
public function getComponentNames(array $components = []) {
$components = array_filter($components);
if ($components) {
$names = array();
$names = [];
foreach ($components as $type => $list) {
// InstallStorage::getComponentNames returns a list of folders keyed by
// config name.
@ -322,8 +322,8 @@ class LocaleConfigManager {
* Array of configuration object names.
*/
public function getStringNames(array $lids) {
$names = array();
$locations = $this->localeStorage->getLocations(array('sid' => $lids, 'type' => 'configuration'));
$names = [];
$locations = $this->localeStorage->getLocations(['sid' => $lids, 'type' => 'configuration']);
foreach ($locations as $location) {
$names[$location->name] = $location->name;
}
@ -370,15 +370,15 @@ class LocaleConfigManager {
// If translations for a language have not been loaded yet.
if (!isset($this->translations[$name][$langcode])) {
// Preload all translations for this configuration name and language.
$this->translations[$name][$langcode] = array();
foreach ($this->localeStorage->getTranslations(array('language' => $langcode, 'type' => 'configuration', 'name' => $name)) as $string) {
$this->translations[$name][$langcode] = [];
foreach ($this->localeStorage->getTranslations(['language' => $langcode, 'type' => 'configuration', 'name' => $name]) as $string) {
$this->translations[$name][$langcode][$string->context][$string->source] = $string;
}
}
if (!isset($this->translations[$name][$langcode][$context][$source])) {
// There is no translation of the source string in this config location
// to this language for this context.
if ($translation = $this->localeStorage->findTranslation(array('source' => $source, 'context' => $context, 'language' => $langcode))) {
if ($translation = $this->localeStorage->findTranslation(['source' => $source, 'context' => $context, 'language' => $langcode])) {
// Look for a translation of the string. It might have one, but not
// be saved in this configuration location yet.
// If the string has a translation for this context to this language,
@ -393,7 +393,7 @@ class LocaleConfigManager {
// location so it can be translated, and the string is faster to look
// for next time.
$translation = $this->localeStorage
->createString(array('source' => $source, 'context' => $context))
->createString(['source' => $source, 'context' => $context])
->addLocation('configuration', $name)
->save();
}
@ -418,7 +418,7 @@ class LocaleConfigManager {
* @return $this
*/
public function reset() {
$this->translations = array();
$this->translations = [];
return $this;
}
@ -442,7 +442,7 @@ class LocaleConfigManager {
$this->translateString($name, $langcode, $source, $context);
if ($string = $this->translations[$name][$langcode][$context][$source]) {
if (!$string->isTranslation()) {
$conditions = array('lid' => $string->lid, 'language' => $langcode);
$conditions = ['lid' => $string->lid, 'language' => $langcode];
$translation = $this->localeStorage->createTranslation($conditions);
$this->translations[$name][$langcode][$context][$source] = $translation;
return $translation;
@ -564,7 +564,7 @@ class LocaleConfigManager {
* Total number of configuration override and active configuration objects
* updated (saved or removed).
*/
public function updateConfigTranslations(array $names, array $langcodes = array()) {
public function updateConfigTranslations(array $names, array $langcodes = []) {
$langcodes = $langcodes ? $langcodes : array_keys($this->languageManager->getLanguages());
$count = 0;
foreach ($names as $name) {
@ -589,7 +589,7 @@ class LocaleConfigManager {
$data = $this->filterOverride($override->get(), $translatable);
if (!empty($processed)) {
// Merge in the Locale managed translations with existing data.
$data = NestedArray::mergeDeepArray(array($data, $processed), TRUE);
$data = NestedArray::mergeDeepArray([$data, $processed], TRUE);
}
if (empty($data) && !$override->isNew()) {
// The configuration override contains Locale overrides that no
@ -607,7 +607,7 @@ class LocaleConfigManager {
// If the language code is the active storage language, we should
// update. If it is English, we should only update if English is also
// translatable.
$active = NestedArray::mergeDeepArray(array($active, $processed), TRUE);
$active = NestedArray::mergeDeepArray([$active, $processed], TRUE);
$this->saveTranslationActive($name, $active);
$count++;
}
@ -629,7 +629,7 @@ class LocaleConfigManager {
* also in $translatable.
*/
protected function filterOverride(array $override_data, array $translatable) {
$filtered_data = array();
$filtered_data = [];
foreach ($override_data as $key => $value) {
if (isset($translatable[$key])) {
// If the translatable default configuration has this key, look further

View file

@ -114,7 +114,7 @@ class LocaleConfigSubscriber implements EventSubscriberInterface {
* override. This allows us to update locale keys for data not in the
* override but still in the active configuration.
*/
protected function updateLocaleStorage(StorableConfigBase $config, $langcode, array $reference_config = array()) {
protected function updateLocaleStorage(StorableConfigBase $config, $langcode, array $reference_config = []) {
$name = $config->getName();
if ($this->localeConfigManager->isSupported($name) && locale_is_translatable($langcode)) {
$translatables = $this->localeConfigManager->getTranslatableDefaultConfig($name);
@ -139,7 +139,7 @@ class LocaleConfigSubscriber implements EventSubscriberInterface {
* override. This allows us to update locale keys for data not in the
* override but still in the active configuration.
*/
protected function processTranslatableData($name, array $config, array $translatable, $langcode, array $reference_config = array()) {
protected function processTranslatableData($name, array $config, array $translatable, $langcode, array $reference_config = []) {
foreach ($translatable as $key => $item) {
if (!isset($config[$key])) {
if (isset($reference_config[$key])) {
@ -148,7 +148,7 @@ class LocaleConfigSubscriber implements EventSubscriberInterface {
continue;
}
if (is_array($item)) {
$reference_config = isset($reference_config[$key]) ? $reference_config[$key] : array();
$reference_config = isset($reference_config[$key]) ? $reference_config[$key] : [];
$this->processTranslatableData($name, $config[$key], $item, $langcode, $reference_config);
}
else {

View file

@ -57,12 +57,12 @@ class LocaleDefaultConfigStorage {
* @param \Drupal\language\ConfigurableLanguageManagerInterface $language_manager
* The language manager.
*/
public function __construct(StorageInterface $config_storage, ConfigurableLanguageManagerInterface $language_manager) {
public function __construct(StorageInterface $config_storage, ConfigurableLanguageManagerInterface $language_manager, $install_profile) {
$this->configStorage = $config_storage;
$this->languageManager = $language_manager;
$this->requiredInstallStorage = new ExtensionInstallStorage($this->configStorage);
$this->optionalInstallStorage = new ExtensionInstallStorage($this->configStorage, ExtensionInstallStorage::CONFIG_OPTIONAL_DIRECTORY);
$this->requiredInstallStorage = new ExtensionInstallStorage($this->configStorage, ExtensionInstallStorage::CONFIG_INSTALL_DIRECTORY, ExtensionInstallStorage::DEFAULT_COLLECTION, TRUE, $install_profile);
$this->optionalInstallStorage = new ExtensionInstallStorage($this->configStorage, ExtensionInstallStorage::CONFIG_OPTIONAL_DIRECTORY, ExtensionInstallStorage::DEFAULT_COLLECTION, TRUE, $install_profile);
}
/**

View file

@ -31,7 +31,7 @@ class LocaleEvent extends Event {
* @param array $lids
* (optional) List of string identifiers that have been updated / created.
*/
public function __construct(array $lang_codes, array $lids = array()) {
public function __construct(array $lang_codes, array $lids = []) {
$this->langCodes = $lang_codes;
$this->lids = $lids;
}

View file

@ -99,7 +99,7 @@ class LocaleLookup extends CacheCollector {
$this->cache = $cache;
$this->lock = $lock;
$this->tags = array('locale');
$this->tags = ['locale'];
$this->requestStack = $request_stack;
}
@ -123,7 +123,7 @@ class LocaleLookup extends CacheCollector {
// cache misses that need to be written into the cache. Prevent that by
// resetting that list. All that happens in such a case are a few uncached
// translation lookups.
$this->keysToPersist = array();
$this->keysToPersist = [];
}
return $this->cid;
}
@ -132,11 +132,11 @@ class LocaleLookup extends CacheCollector {
* {@inheritdoc}
*/
protected function resolveCacheMiss($offset) {
$translation = $this->stringStorage->findTranslation(array(
$translation = $this->stringStorage->findTranslation([
'language' => $this->langcode,
'source' => $offset,
'context' => $this->context,
));
]);
if ($translation) {
$value = !empty($translation->translation) ? $translation->translation : TRUE;
@ -144,25 +144,25 @@ class LocaleLookup extends CacheCollector {
else {
// We don't have the source string, update the {locales_source} table to
// indicate the string is not translated.
$this->stringStorage->createString(array(
$this->stringStorage->createString([
'source' => $offset,
'context' => $this->context,
'version' => \Drupal::VERSION,
))->addLocation('path', $this->requestStack->getCurrentRequest()->getRequestUri())->save();
])->addLocation('path', $this->requestStack->getCurrentRequest()->getRequestUri())->save();
$value = TRUE;
}
// If there is no translation available for the current language then use
// language fallback to try other translations.
if ($value === TRUE) {
$fallbacks = $this->languageManager->getFallbackCandidates(array('langcode' => $this->langcode, 'operation' => 'locale_lookup', 'data' => $offset));
$fallbacks = $this->languageManager->getFallbackCandidates(['langcode' => $this->langcode, 'operation' => 'locale_lookup', 'data' => $offset]);
if (!empty($fallbacks)) {
foreach ($fallbacks as $langcode) {
$translation = $this->stringStorage->findTranslation(array(
$translation = $this->stringStorage->findTranslation([
'language' => $langcode,
'source' => $offset,
'context' => $this->context,
));
]);
if ($translation && !empty($translation->translation)) {
$value = $translation->translation;

View file

@ -21,7 +21,7 @@ class LocaleProjectStorage implements LocaleProjectStorageInterface {
*
* @var array
*/
protected $cache = array();
protected $cache = [];
/**
* Cache status flag.
@ -36,7 +36,7 @@ class LocaleProjectStorage implements LocaleProjectStorageInterface {
* @param \Drupal\Core\KeyValueStore\KeyValueFactoryInterface $key_value_factory
* The key value store to use.
*/
function __construct(KeyValueFactoryInterface $key_value_factory) {
public function __construct(KeyValueFactoryInterface $key_value_factory) {
$this->keyValueStore = $key_value_factory->get('locale.project');
}
@ -44,7 +44,7 @@ class LocaleProjectStorage implements LocaleProjectStorageInterface {
* {@inheritdoc}
*/
public function get($key, $default = NULL) {
$values = $this->getMultiple(array($key));
$values = $this->getMultiple([$key]);
return isset($values[$key]) ? $values[$key] : $default;
}
@ -52,8 +52,8 @@ class LocaleProjectStorage implements LocaleProjectStorageInterface {
* {@inheritdoc}
*/
public function getMultiple(array $keys) {
$values = array();
$load = array();
$values = [];
$load = [];
foreach ($keys as $key) {
// Check if we have a value in the cache.
if (isset($this->cache[$key])) {
@ -87,7 +87,7 @@ class LocaleProjectStorage implements LocaleProjectStorageInterface {
* {@inheritdoc}
*/
public function set($key, $value) {
$this->setMultiple(array($key => $value));
$this->setMultiple([$key => $value]);
}
/**
@ -104,7 +104,7 @@ class LocaleProjectStorage implements LocaleProjectStorageInterface {
* {@inheritdoc}
*/
public function delete($key) {
$this->deleteMultiple(array($key));
$this->deleteMultiple([$key]);
}
/**
@ -121,7 +121,7 @@ class LocaleProjectStorage implements LocaleProjectStorageInterface {
* {@inheritdoc}
*/
public function resetCache() {
$this->cache = array();
$this->cache = [];
static::$all = FALSE;
}

View file

@ -40,7 +40,7 @@ class LocaleTranslation implements TranslatorInterface, DestructableInterface {
* Array of \Drupal\locale\LocaleLookup objects indexed by language code
* and context.
*/
protected $translations = array();
protected $translations = [];
/**
* The cache backend that should be used.
@ -137,7 +137,7 @@ class LocaleTranslation implements TranslatorInterface, DestructableInterface {
*/
public function reset() {
unset($this->translateEnglish);
$this->translations = array();
$this->translations = [];
}
/**

View file

@ -92,7 +92,7 @@ class PluralFormula implements PluralFormulaInterface {
/**
* Loads the formulae and stores them on the PluralFormula object if not set.
*
* @return []
* @return array
*/
protected function loadFormulae() {
if (!isset($this->formulae)) {

View file

@ -45,7 +45,7 @@ class PoDatabaseReader implements PoReaderInterface {
* Constructor, initializes with default options.
*/
public function __construct() {
$this->setOptions(array());
$this->setOptions([]);
}
/**
@ -73,11 +73,11 @@ class PoDatabaseReader implements PoReaderInterface {
* Set the options for the current reader.
*/
public function setOptions(array $options) {
$options += array(
$options += [
'customized' => FALSE,
'not_customized' => FALSE,
'not_translated' => FALSE,
);
];
$this->options = $options;
}
@ -104,7 +104,7 @@ class PoDatabaseReader implements PoReaderInterface {
private function loadStrings() {
$langcode = $this->langcode;
$options = $this->options;
$conditions = array();
$conditions = [];
if (array_sum($options) == 0) {
// If user asked to not include anything in the translation files,

View file

@ -89,14 +89,14 @@ class PoDatabaseWriter implements PoWriterInterface {
* @param array $report
* Associative array with result information.
*/
public function setReport($report = array()) {
$report += array(
public function setReport($report = []) {
$report += [
'additions' => 0,
'updates' => 0,
'deletes' => 0,
'skips' => 0,
'strings' => array(),
);
'strings' => [],
];
$this->report = $report;
}
@ -112,15 +112,15 @@ class PoDatabaseWriter implements PoWriterInterface {
*/
public function setOptions(array $options) {
if (!isset($options['overwrite_options'])) {
$options['overwrite_options'] = array();
$options['overwrite_options'] = [];
}
$options['overwrite_options'] += array(
$options['overwrite_options'] += [
'not_customized' => FALSE,
'customized' => FALSE,
);
$options += array(
];
$options += [
'customized' => LOCALE_NOT_CUSTOMIZED,
);
];
$this->options = $options;
}
@ -148,7 +148,7 @@ class PoDatabaseWriter implements PoWriterInterface {
*/
public function setHeader(PoHeader $header) {
$this->header = $header;
$locale_plurals = \Drupal::state()->get('locale.translation.plurals') ?: array();
$locale_plurals = \Drupal::state()->get('locale.translation.plurals') ?: [];
// Check for options.
$options = $this->getOptions();
@ -205,10 +205,10 @@ class PoDatabaseWriter implements PoWriterInterface {
*/
private function importString(PoItem $item) {
// Initialize overwrite options if not set.
$this->options['overwrite_options'] += array(
$this->options['overwrite_options'] += [
'not_customized' => FALSE,
'customized' => FALSE,
);
];
$overwrite_options = $this->options['overwrite_options'];
$customized = $this->options['customized'];
@ -217,17 +217,17 @@ class PoDatabaseWriter implements PoWriterInterface {
$translation = $item->getTranslation();
// Look up the source string and any existing translation.
$strings = \Drupal::service('locale.storage')->getTranslations(array(
$strings = \Drupal::service('locale.storage')->getTranslations([
'language' => $this->langcode,
'source' => $source,
'context' => $context,
));
]);
$string = reset($strings);
if (!empty($translation)) {
// Skip this string unless it passes a check for dangerous code.
if (!locale_string_is_safe($translation)) {
\Drupal::logger('locale')->error('Import of string "%string" was skipped because of disallowed or malformed HTML.', array('%string' => $translation));
\Drupal::logger('locale')->error('Import of string "%string" was skipped because of disallowed or malformed HTML.', ['%string' => $translation]);
$this->report['skips']++;
return 0;
}
@ -235,10 +235,10 @@ class PoDatabaseWriter implements PoWriterInterface {
$string->setString($translation);
if ($string->isNew()) {
// No translation in this language.
$string->setValues(array(
$string->setValues([
'language' => $this->langcode,
'customized' => $customized,
));
]);
$string->save();
$this->report['additions']++;
}
@ -253,14 +253,14 @@ class PoDatabaseWriter implements PoWriterInterface {
}
else {
// No such source string in the database yet.
$string = \Drupal::service('locale.storage')->createString(array('source' => $source, 'context' => $context))
$string = \Drupal::service('locale.storage')->createString(['source' => $source, 'context' => $context])
->save();
\Drupal::service('locale.storage')->createTranslation(array(
\Drupal::service('locale.storage')->createTranslation([
'lid' => $string->getId(),
'language' => $this->langcode,
'translation' => $translation,
'customized' => $customized,
))->save();
])->save();
$this->report['additions']++;
$this->report['strings'][] = $string->getId();

View file

@ -36,7 +36,7 @@ class TranslationsStream extends LocalStream {
/**
* {@inheritdoc}
*/
function getDirectoryPath() {
public function getDirectoryPath() {
return \Drupal::config('locale.settings')->get('translation.path');
}
@ -45,7 +45,7 @@ class TranslationsStream extends LocalStream {
* @throws \LogicException
* PO files URL should not be public.
*/
function getExternalUrl() {
public function getExternalUrl() {
throw new \LogicException('PO files URL should not be public.');
}

View file

@ -57,7 +57,7 @@ abstract class StringBase implements StringInterface {
* @param object|array $values
* Object or array with initial values.
*/
public function __construct($values = array()) {
public function __construct($values = []) {
$this->setValues((array) $values);
}
@ -137,7 +137,7 @@ abstract class StringBase implements StringInterface {
* {@inheritdoc}
*/
public function getValues(array $fields) {
$values = array();
$values = [];
foreach ($fields as $field) {
if (isset($this->$field)) {
$values[$field] = $this->$field;
@ -151,12 +151,12 @@ abstract class StringBase implements StringInterface {
*/
public function getLocations($check_only = FALSE) {
if (!isset($this->locations) && !$check_only) {
$this->locations = array();
foreach ($this->getStorage()->getLocations(array('sid' => $this->getId())) as $location) {
$this->locations = [];
foreach ($this->getStorage()->getLocations(['sid' => $this->getId()]) as $location) {
$this->locations[$location->type][$location->name] = $location->lid;
}
}
return isset($this->locations) ? $this->locations : array();
return isset($this->locations) ? $this->locations : [];
}
/**

View file

@ -21,7 +21,7 @@ class StringDatabaseStorage implements StringStorageInterface {
*
* @var array
*/
protected $options = array();
protected $options = [];
/**
* Constructs a new StringDatabaseStorage class.
@ -31,7 +31,7 @@ class StringDatabaseStorage implements StringStorageInterface {
* @param array $options
* (optional) Any additional database connection options to use in queries.
*/
public function __construct(Connection $connection, array $options = array()) {
public function __construct(Connection $connection, array $options = []) {
$this->connection = $connection;
$this->options = $options;
}
@ -39,15 +39,15 @@ class StringDatabaseStorage implements StringStorageInterface {
/**
* {@inheritdoc}
*/
public function getStrings(array $conditions = array(), array $options = array()) {
public function getStrings(array $conditions = [], array $options = []) {
return $this->dbStringLoad($conditions, $options, 'Drupal\locale\SourceString');
}
/**
* {@inheritdoc}
*/
public function getTranslations(array $conditions = array(), array $options = array()) {
return $this->dbStringLoad($conditions, array('translation' => TRUE) + $options, 'Drupal\locale\TranslationString');
public function getTranslations(array $conditions = [], array $options = []) {
return $this->dbStringLoad($conditions, ['translation' => TRUE] + $options, 'Drupal\locale\TranslationString');
}
/**
@ -69,7 +69,7 @@ class StringDatabaseStorage implements StringStorageInterface {
* {@inheritdoc}
*/
public function findTranslation(array $conditions) {
$values = $this->dbStringSelect($conditions, array('translation' => TRUE))
$values = $this->dbStringSelect($conditions, ['translation' => TRUE])
->execute()
->fetchAssoc();
@ -84,7 +84,7 @@ class StringDatabaseStorage implements StringStorageInterface {
/**
* {@inheritdoc}
*/
public function getLocations(array $conditions = array()) {
public function getLocations(array $conditions = []) {
$query = $this->connection->select('locales_location', 'l', $this->options)
->fields('l');
foreach ($conditions as $field => $value) {
@ -142,14 +142,14 @@ class StringDatabaseStorage implements StringStorageInterface {
// Make sure that the name isn't longer than 255 characters.
$name = substr($name, 0, 255);
if (!$lid) {
$this->dbDelete('locales_location', array('sid' => $string->getId(), 'type' => $type, 'name' => $name))
$this->dbDelete('locales_location', ['sid' => $string->getId(), 'type' => $type, 'name' => $name])
->execute();
}
elseif ($lid === TRUE) {
// This is a new location to add, take care not to duplicate.
$this->connection->merge('locales_location', $this->options)
->keys(array('sid' => $string->getId(), 'type' => $type, 'name' => $name))
->fields(array('version' => \Drupal::VERSION))
->keys(['sid' => $string->getId(), 'type' => $type, 'name' => $name])
->fields(['version' => \Drupal::VERSION])
->execute();
$created = TRUE;
}
@ -176,7 +176,7 @@ class StringDatabaseStorage implements StringStorageInterface {
$string->setVersion($version);
$this->connection->update('locales_source', $this->options)
->condition('lid', $string->getId())
->fields(array('version' => $version))
->fields(['version' => $version])
->execute();
}
}
@ -203,11 +203,11 @@ class StringDatabaseStorage implements StringStorageInterface {
* {@inheritdoc}
*/
public function deleteStrings($conditions) {
$lids = $this->dbStringSelect($conditions, array('fields' => array('lid')))->execute()->fetchCol();
$lids = $this->dbStringSelect($conditions, ['fields' => ['lid']])->execute()->fetchCol();
if ($lids) {
$this->dbDelete('locales_target', array('lid' => $lids))->execute();
$this->dbDelete('locales_source', array('lid' => $lids))->execute();
$this->dbDelete('locales_location', array('sid' => $lids))->execute();
$this->dbDelete('locales_target', ['lid' => $lids])->execute();
$this->dbDelete('locales_source', ['lid' => $lids])->execute();
$this->dbDelete('locales_location', ['sid' => $lids])->execute();
}
}
@ -221,18 +221,18 @@ class StringDatabaseStorage implements StringStorageInterface {
/**
* {@inheritdoc}
*/
public function createString($values = array()) {
return new SourceString($values + array('storage' => $this));
public function createString($values = []) {
return new SourceString($values + ['storage' => $this]);
}
/**
* {@inheritdoc}
*/
public function createTranslation($values = array()) {
return new TranslationString($values + array(
public function createTranslation($values = []) {
return new TranslationString($values + [
'storage' => $this,
'is_new' => TRUE,
));
]);
}
/**
@ -250,10 +250,10 @@ class StringDatabaseStorage implements StringStorageInterface {
* table fields)
*/
protected function dbFieldTable($field) {
if (in_array($field, array('language', 'translation', 'customized'))) {
if (in_array($field, ['language', 'translation', 'customized'])) {
return 't';
}
elseif (in_array($field, array('type', 'name'))) {
elseif (in_array($field, ['type', 'name'])) {
return 'l';
}
else {
@ -290,16 +290,16 @@ class StringDatabaseStorage implements StringStorageInterface {
*/
protected function dbStringKeys($string) {
if ($string->isSource()) {
$keys = array('lid');
$keys = ['lid'];
}
elseif ($string->isTranslation()) {
$keys = array('lid', 'language');
$keys = ['lid', 'language'];
}
if (!empty($keys) && ($values = $string->getValues($keys)) && count($keys) == count($values)) {
return $values;
}
else {
return array();
return [];
}
}
@ -317,7 +317,7 @@ class StringDatabaseStorage implements StringStorageInterface {
* Array of objects of the class requested.
*/
protected function dbStringLoad(array $conditions, array $options, $class) {
$strings = array();
$strings = [];
$result = $this->dbStringSelect($conditions, $options)->execute();
foreach ($result as $item) {
/** @var \Drupal\locale\StringInterface $string */
@ -349,7 +349,7 @@ class StringDatabaseStorage implements StringStorageInterface {
* @return \Drupal\Core\Database\Query\Select
* Query object with all the tables, fields and conditions.
*/
protected function dbStringSelect(array $conditions, array $options = array()) {
protected function dbStringSelect(array $conditions, array $options = []) {
// Start building the query with source table and check whether we need to
// join the target table too.
$query = $this->connection->select('locales_source', 's', $this->options)
@ -376,9 +376,9 @@ class StringDatabaseStorage implements StringStorageInterface {
if ($join) {
if (isset($conditions['language'])) {
// If we've got a language condition, we use it for the join.
$query->$join('locales_target', 't', "t.lid = s.lid AND t.language = :langcode", array(
$query->$join('locales_target', 't', "t.lid = s.lid AND t.language = :langcode", [
':langcode' => $conditions['language'],
));
]);
unset($conditions['language']);
}
else {
@ -387,7 +387,7 @@ class StringDatabaseStorage implements StringStorageInterface {
}
if (!empty($options['translation'])) {
// We cannot just add all fields because 'lid' may get null values.
$query->fields('t', array('language', 'translation', 'customized'));
$query->fields('t', ['language', 'translation', 'customized']);
}
}
@ -396,8 +396,8 @@ class StringDatabaseStorage implements StringStorageInterface {
// array so we can consistently use IN conditions.
if (isset($conditions['type']) || isset($conditions['name'])) {
$subquery = $this->connection->select('locales_location', 'l', $this->options)
->fields('l', array('sid'));
foreach (array('type', 'name') as $field) {
->fields('l', ['sid']);
foreach (['type', 'name'] as $field) {
if (isset($conditions[$field])) {
$subquery->condition('l.' . $field, (array) $conditions[$field], 'IN');
unset($conditions[$field]);
@ -417,8 +417,8 @@ class StringDatabaseStorage implements StringStorageInterface {
// Conditions for target fields when doing an outer join only make
// sense if we add also OR field IS NULL.
$query->condition(db_or()
->condition($field_alias, (array) $value, 'IN')
->isNull($field_alias)
->condition($field_alias, (array) $value, 'IN')
->isNull($field_alias)
);
}
else {
@ -463,12 +463,12 @@ class StringDatabaseStorage implements StringStorageInterface {
*/
protected function dbStringInsert($string) {
if ($string->isSource()) {
$string->setValues(array('context' => '', 'version' => 'none'), FALSE);
$fields = $string->getValues(array('source', 'context', 'version'));
$string->setValues(['context' => '', 'version' => 'none'], FALSE);
$fields = $string->getValues(['source', 'context', 'version']);
}
elseif ($string->isTranslation()) {
$string->setValues(array('customized' => 0), FALSE);
$fields = $string->getValues(array('lid', 'language', 'translation', 'customized'));
$string->setValues(['customized' => 0], FALSE);
$fields = $string->getValues(['lid', 'language', 'translation', 'customized']);
}
if (!empty($fields)) {
return $this->connection->insert($this->dbStringTable($string), $this->options)
@ -495,10 +495,10 @@ class StringDatabaseStorage implements StringStorageInterface {
*/
protected function dbStringUpdate($string) {
if ($string->isSource()) {
$values = $string->getValues(array('source', 'context', 'version'));
$values = $string->getValues(['source', 'context', 'version']);
}
elseif ($string->isTranslation()) {
$values = $string->getValues(array('translation', 'customized'));
$values = $string->getValues(['translation', 'customized']);
}
if (!empty($values) && $keys = $this->dbStringKeys($string)) {
return $this->connection->merge($this->dbStringTable($string), $this->options)
@ -533,7 +533,7 @@ class StringDatabaseStorage implements StringStorageInterface {
/**
* Executes an arbitrary SELECT query string with the injected options.
*/
protected function dbExecute($query, array $args = array()) {
protected function dbExecute($query, array $args = []) {
return $this->connection->query($query, $args, $this->options);
}

View file

@ -27,7 +27,7 @@ interface StringStorageInterface {
* @return array
* Array of \Drupal\locale\StringInterface objects matching the conditions.
*/
public function getStrings(array $conditions = array(), array $options = array());
public function getStrings(array $conditions = [], array $options = []);
/**
* Loads multiple string translation objects.
@ -44,7 +44,7 @@ interface StringStorageInterface {
*
* @see \Drupal\locale\StringStorageInterface::getStrings()
*/
public function getTranslations(array $conditions = array(), array $options = array());
public function getTranslations(array $conditions = [], array $options = []);
/**
* Loads string location information.
@ -61,7 +61,7 @@ interface StringStorageInterface {
*
* @see \Drupal\locale\StringStorageInterface::getStrings()
*/
public function getLocations(array $conditions = array());
public function getLocations(array $conditions = []);
/**
* Loads a string source object, fast query.
@ -164,7 +164,7 @@ interface StringStorageInterface {
* @return \Drupal\locale\SourceString
* New source string object.
*/
public function createString($values = array());
public function createString($values = []);
/**
* Creates a string translation object bound to this storage but not saved.
@ -175,6 +175,6 @@ interface StringStorageInterface {
* @return \Drupal\locale\TranslationString
* New string translation object.
*/
public function createTranslation($values = array());
public function createTranslation($values = []);
}

View file

@ -18,13 +18,13 @@ class LocaleConfigTranslationImportTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('language', 'locale_test_translate');
public static $modules = ['language', 'locale_test_translate'];
/**
* Test update changes configuration translations if enabled after language.
*/
public function testConfigTranslationImport() {
$admin_user = $this->drupalCreateUser(array('administer modules', 'administer site configuration', 'administer languages', 'access administration pages', 'administer permissions'));
$admin_user = $this->drupalCreateUser(['administer modules', 'administer site configuration', 'administer languages', 'access administration pages', 'administer permissions']);
$this->drupalLogin($admin_user);
// Add a language. The Afrikaans translation file of locale_test_translate
@ -32,7 +32,7 @@ class LocaleConfigTranslationImportTest extends WebTestBase {
ConfigurableLanguage::createFromLangcode('af')->save();
// Enable locale module.
$this->container->get('module_installer')->install(array('locale'));
$this->container->get('module_installer')->install(['locale']);
$this->resetAll();
// Enable import of translations. By default this is disabled for automated
@ -42,9 +42,9 @@ class LocaleConfigTranslationImportTest extends WebTestBase {
->save();
// Add translation permissions now that the locale module has been enabled.
$edit = array(
$edit = [
'authenticated[translate interface]' => 'translate interface',
);
];
$this->drupalPostForm('admin/people/permissions', $edit, t('Save permissions'));
// Check and update the translation status. This will import the Afrikaans
@ -57,7 +57,7 @@ class LocaleConfigTranslationImportTest extends WebTestBase {
$status['drupal']['af']->type = 'current';
\Drupal::state()->set('locale.translation_status', $status);
$this->drupalPostForm('admin/reports/translations', array(), t('Update translations'));
$this->drupalPostForm('admin/reports/translations', [], t('Update translations'));
// Check if configuration translations have been imported.
$override = \Drupal::languageManager()->getLanguageConfigOverride('af', 'system.maintenance');
@ -77,7 +77,7 @@ class LocaleConfigTranslationImportTest extends WebTestBase {
// import. Test that this override is in place.
$this->assertFalse($this->config('locale.settings')->get('translation.import_enabled'), 'Translations imports are disabled by default in the Testing profile.');
$admin_user = $this->drupalCreateUser(array('administer modules', 'administer site configuration', 'administer languages', 'access administration pages', 'administer permissions', 'translate configuration'));
$admin_user = $this->drupalCreateUser(['administer modules', 'administer site configuration', 'administer languages', 'access administration pages', 'administer permissions', 'translate configuration']);
$this->drupalLogin($admin_user);
// Enable import of translations. By default this is disabled for automated
@ -90,7 +90,7 @@ class LocaleConfigTranslationImportTest extends WebTestBase {
$this->drupalPostForm('admin/config/regional/language/add', ['predefined_langcode' => 'af'], t('Add language'));
// Add the system branding block to the page.
$this->drupalPlaceBlock('system_branding_block', array('region' => 'header', 'id' => 'site-branding'));
$this->drupalPlaceBlock('system_branding_block', ['region' => 'header', 'id' => 'site-branding']);
$this->drupalPostForm('admin/config/system/site-information', ['site_slogan' => 'Test site slogan'], 'Save configuration');
$this->drupalPostForm('admin/config/system/site-information/translate/af/edit', ['translation[config_names][system.site][slogan]' => 'Test site slogan in Afrikaans'], 'Save translation');
@ -109,7 +109,7 @@ class LocaleConfigTranslationImportTest extends WebTestBase {
->save();
// Install any module.
$this->drupalPostForm('admin/modules', ['modules[Core][dblog][enable]' => 'dblog'], t('Install'));
$this->drupalPostForm('admin/modules', ['modules[dblog][enable]' => 'dblog'], t('Install'));
$this->assertText('Module Database Logging has been enabled.');
// Get the front page and ensure that the translated configuration still
@ -130,12 +130,12 @@ class LocaleConfigTranslationImportTest extends WebTestBase {
/**
* Test removing a string from Locale deletes configuration translations.
*/
function testLocaleRemovalAndConfigOverrideDelete() {
public function testLocaleRemovalAndConfigOverrideDelete() {
// Enable the locale module.
$this->container->get('module_installer')->install(['locale']);
$this->resetAll();
$admin_user = $this->drupalCreateUser(array('administer modules', 'administer site configuration', 'administer languages', 'access administration pages', 'administer permissions', 'translate interface'));
$admin_user = $this->drupalCreateUser(['administer modules', 'administer site configuration', 'administer languages', 'access administration pages', 'administer permissions', 'translate interface']);
$this->drupalLogin($admin_user);
// Enable import of translations. By default this is disabled for automated
@ -153,7 +153,7 @@ class LocaleConfigTranslationImportTest extends WebTestBase {
// Remove the string from translation to simulate a Locale removal. Note
// that is no current way of doing this in the UI.
$locale_storage = \Drupal::service('locale.storage');
$string = $locale_storage->findString(array('source' => 'Locale can translate'));
$string = $locale_storage->findString(['source' => 'Locale can translate']);
\Drupal::service('locale.storage')->delete($string);
// Force a rebuild of config translations.
$count = Locale::config()->updateConfigTranslations(['locale_test_translate.settings'], ['af']);
@ -167,12 +167,12 @@ class LocaleConfigTranslationImportTest extends WebTestBase {
/**
* Test removing a string from Locale changes configuration translations.
*/
function testLocaleRemovalAndConfigOverridePreserve() {
public function testLocaleRemovalAndConfigOverridePreserve() {
// Enable the locale module.
$this->container->get('module_installer')->install(['locale']);
$this->resetAll();
$admin_user = $this->drupalCreateUser(array('administer modules', 'administer site configuration', 'administer languages', 'access administration pages', 'administer permissions', 'translate interface'));
$admin_user = $this->drupalCreateUser(['administer modules', 'administer site configuration', 'administer languages', 'access administration pages', 'administer permissions', 'translate interface']);
$this->drupalLogin($admin_user);
// Enable import of translations. By default this is disabled for automated
@ -198,18 +198,18 @@ class LocaleConfigTranslationImportTest extends WebTestBase {
$this->assertEqual($expected, $override->get());
// Set the translated string to empty.
$search = array(
$search = [
'string' => 'Locale can translate',
'langcode' => 'af',
'translation' => 'all',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$textareas = $this->xpath('//textarea');
$textarea = current($textareas);
$lid = (string) $textarea[0]['name'];
$edit = array(
$edit = [
$lid => '',
);
];
$this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));
$override = \Drupal::languageManager()->getLanguageConfigOverride('af', 'locale_test_translate.settings');

View file

@ -24,7 +24,7 @@ class LocaleConfigTranslationTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('locale', 'contact', 'contact_test');
public static $modules = ['locale', 'contact', 'contact_test'];
/**
* {@inheritdoc}
@ -42,15 +42,15 @@ class LocaleConfigTranslationTest extends WebTestBase {
// Add custom language.
$this->langcode = 'xx';
$admin_user = $this->drupalCreateUser(array('administer languages', 'access administration pages', 'translate interface', 'administer modules', 'access site-wide contact form', 'administer contact forms', 'administer site configuration'));
$admin_user = $this->drupalCreateUser(['administer languages', 'access administration pages', 'translate interface', 'administer modules', 'access site-wide contact form', 'administer contact forms', 'administer site configuration']);
$this->drupalLogin($admin_user);
$name = $this->randomMachineName(16);
$edit = array(
$edit = [
'predefined_langcode' => 'custom',
'langcode' => $this->langcode,
'label' => $name,
'direction' => LanguageInterface::DIRECTION_LTR,
);
];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
// Set path prefix.
$edit = ["prefix[$this->langcode]" => $this->langcode];
@ -63,23 +63,23 @@ class LocaleConfigTranslationTest extends WebTestBase {
public function testConfigTranslation() {
// Check that the maintenance message exists and create translation for it.
$source = '@site is currently under maintenance. We should be back shortly. Thank you for your patience.';
$string = $this->storage->findString(array('source' => $source, 'context' => '', 'type' => 'configuration'));
$string = $this->storage->findString(['source' => $source, 'context' => '', 'type' => 'configuration']);
$this->assertTrue($string, 'Configuration strings have been created upon installation.');
// Translate using the UI so configuration is refreshed.
$message = $this->randomMachineName(20);
$search = array(
$search = [
'string' => $string->source,
'langcode' => $this->langcode,
'translation' => 'all',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$textareas = $this->xpath('//textarea');
$textarea = current($textareas);
$lid = (string) $textarea[0]['name'];
$edit = array(
$edit = [
$lid => $message,
);
];
$this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));
// Get translation and check we've only got the message.
@ -88,22 +88,22 @@ class LocaleConfigTranslationTest extends WebTestBase {
$this->assertEqual($translation['message'], $message);
// Check default medium date format exists and create a translation for it.
$string = $this->storage->findString(array('source' => 'D, m/d/Y - H:i', 'context' => 'PHP date format', 'type' => 'configuration'));
$string = $this->storage->findString(['source' => 'D, m/d/Y - H:i', 'context' => 'PHP date format', 'type' => 'configuration']);
$this->assertTrue($string, 'Configuration date formats have been created upon installation.');
// Translate using the UI so configuration is refreshed.
$search = array(
$search = [
'string' => $string->source,
'langcode' => $this->langcode,
'translation' => 'all',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$textareas = $this->xpath('//textarea');
$textarea = current($textareas);
$lid = (string) $textarea[0]['name'];
$edit = array(
$edit = [
$lid => 'D',
);
];
$this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));
$translation = \Drupal::languageManager()->getLanguageConfigOverride($this->langcode, 'core.date_format.medium')->get();
@ -115,14 +115,14 @@ class LocaleConfigTranslationTest extends WebTestBase {
$this->assertEqual($formatted_date, 'Tue', 'Got the right formatted date using the date format translation pattern.');
// Assert strings from image module config are not available.
$string = $this->storage->findString(array('source' => 'Medium (220×220)', 'context' => '', 'type' => 'configuration'));
$string = $this->storage->findString(['source' => 'Medium (220×220)', 'context' => '', 'type' => 'configuration']);
$this->assertFalse($string, 'Configuration strings have been created upon installation.');
// Enable the image module.
$this->drupalPostForm('admin/modules', array('modules[Field types][image][enable]' => "1"), t('Install'));
$this->drupalPostForm('admin/modules', ['modules[image][enable]' => "1"], t('Install'));
$this->rebuildContainer();
$string = $this->storage->findString(array('source' => 'Medium (220×220)', 'context' => '', 'type' => 'configuration'));
$string = $this->storage->findString(['source' => 'Medium (220×220)', 'context' => '', 'type' => 'configuration']);
$this->assertTrue($string, 'Configuration strings have been created upon installation.');
$locations = $string->getLocations();
$this->assertTrue(isset($locations['configuration']) && isset($locations['configuration']['image.style.medium']), 'Configuration string has been created with the right location');
@ -136,17 +136,17 @@ class LocaleConfigTranslationTest extends WebTestBase {
// Translate using the UI so configuration is refreshed.
$image_style_label = $this->randomMachineName(20);
$search = array(
$search = [
'string' => $string->source,
'langcode' => $this->langcode,
'translation' => 'all',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$textarea = current($this->xpath('//textarea'));
$lid = (string) $textarea[0]['name'];
$edit = array(
$edit = [
$lid => $image_style_label,
);
];
$this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));
// Check the right single translation has been created.
@ -159,8 +159,8 @@ class LocaleConfigTranslationTest extends WebTestBase {
$this->assertEqual($translation['label'], $image_style_label, 'Got the right translation for image style name after translation');
// Uninstall the module.
$this->drupalPostForm('admin/modules/uninstall', array('uninstall[image]' => "image"), t('Uninstall'));
$this->drupalPostForm(NULL, array(), t('Uninstall'));
$this->drupalPostForm('admin/modules/uninstall', ['uninstall[image]' => "image"], t('Uninstall'));
$this->drupalPostForm(NULL, [], t('Uninstall'));
// Ensure that the translated configuration has been removed.
$override = \Drupal::languageManager()->getLanguageConfigOverride('xx', 'image.style.medium');
@ -168,17 +168,17 @@ class LocaleConfigTranslationTest extends WebTestBase {
// Translate default category using the UI so configuration is refreshed.
$category_label = $this->randomMachineName(20);
$search = array(
$search = [
'string' => 'Website feedback',
'langcode' => $this->langcode,
'translation' => 'all',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$textarea = current($this->xpath('//textarea'));
$lid = (string) $textarea[0]['name'];
$edit = array(
$edit = [
$lid => $category_label,
);
];
$this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));
// Check if this category displayed in this language will use the
@ -198,12 +198,12 @@ class LocaleConfigTranslationTest extends WebTestBase {
public function testOptionalConfiguration() {
$this->assertNodeConfig(FALSE, FALSE);
// Enable the node module.
$this->drupalPostForm('admin/modules', ['modules[Core][node][enable]' => "1"], t('Install'));
$this->drupalPostForm('admin/modules', ['modules[node][enable]' => "1"], t('Install'));
$this->drupalPostForm(NULL, [], t('Continue'));
$this->rebuildContainer();
$this->assertNodeConfig(TRUE, FALSE);
// Enable the views module (which node provides some optional config for).
$this->drupalPostForm('admin/modules', ['modules[Core][views][enable]' => "1"], t('Install'));
$this->drupalPostForm('admin/modules', ['modules[views][enable]' => "1"], t('Install'));
$this->rebuildContainer();
$this->assertNodeConfig(TRUE, TRUE);
}

View file

@ -1,201 +0,0 @@
<?php
namespace Drupal\locale\Tests;
use Drupal\simpletest\WebTestBase;
use Drupal\Core\Language\LanguageInterface;
/**
* Tests you can enable multilingual support on content types and configure a
* language for a node.
*
* @group locale
*/
class LocaleContentTest extends WebTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('node', 'locale');
/**
* Verifies that machine name fields are always LTR.
*/
public function testMachineNameLTR() {
// User to add and remove language.
$admin_user = $this->drupalCreateUser(array('administer languages', 'administer content types', 'access administration pages', 'administer site configuration'));
// Log in as admin.
$this->drupalLogin($admin_user);
// Verify that the machine name field is LTR for a new content type.
$this->drupalGet('admin/structure/types/add');
$this->assertFieldByXpath('//input[@name="type" and @dir="ltr"]', NULL, 'The machine name field is LTR when no additional language is configured.');
// Install the Arabic language (which is RTL) and configure as the default.
$edit = array();
$edit['predefined_langcode'] = 'ar';
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));
$edit = array(
'site_default_language' => 'ar',
);
$this->drupalPostForm('admin/config/regional/language', $edit, t('Save configuration'));
// Verify that the machine name field is still LTR for a new content type.
$this->drupalGet('admin/structure/types/add');
$this->assertFieldByXpath('//input[@name="type" and @dir="ltr"]', NULL, 'The machine name field is LTR when the default language is RTL.');
}
/**
* Test if a content type can be set to multilingual and language is present.
*/
public function testContentTypeLanguageConfiguration() {
$type1 = $this->drupalCreateContentType();
$type2 = $this->drupalCreateContentType();
// User to add and remove language.
$admin_user = $this->drupalCreateUser(array('administer languages', 'administer content types', 'access administration pages'));
// User to create a node.
$web_user = $this->drupalCreateUser(array("create {$type1->id()} content", "create {$type2->id()} content", "edit any {$type2->id()} content"));
// Add custom language.
$this->drupalLogin($admin_user);
// Code for the language.
$langcode = 'xx';
// The English name for the language.
$name = $this->randomMachineName(16);
$edit = array(
'predefined_langcode' => 'custom',
'langcode' => $langcode,
'label' => $name,
'direction' => LanguageInterface::DIRECTION_LTR,
);
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
// Set the content type to use multilingual support.
$this->drupalGet("admin/structure/types/manage/{$type2->id()}");
$this->assertText(t('Language settings'), 'Multilingual support widget present on content type configuration form.');
$edit = array(
'language_configuration[language_alterable]' => TRUE,
);
$this->drupalPostForm("admin/structure/types/manage/{$type2->id()}", $edit, t('Save content type'));
$this->assertRaw(t('The content type %type has been updated.', array('%type' => $type2->label())));
$this->drupalLogout();
\Drupal::languageManager()->reset();
// Verify language selection is not present on the node add form.
$this->drupalLogin($web_user);
$this->drupalGet("node/add/{$type1->id()}");
// Verify language select list is not present.
$this->assertNoFieldByName('langcode[0][value]', NULL, 'Language select not present on the node add form.');
// Verify language selection appears on the node add form.
$this->drupalGet("node/add/{$type2->id()}");
// Verify language select list is present.
$this->assertFieldByName('langcode[0][value]', NULL, 'Language select present on the node add form.');
// Ensure language appears.
$this->assertText($name, 'Language present.');
// Create a node.
$node_title = $this->randomMachineName();
$node_body = $this->randomMachineName();
$edit = array(
'type' => $type2->id(),
'title' => $node_title,
'body' => array(array('value' => $node_body)),
'langcode' => $langcode,
);
$node = $this->drupalCreateNode($edit);
// Edit the content and ensure correct language is selected.
$path = 'node/' . $node->id() . '/edit';
$this->drupalGet($path);
$this->assertRaw('<option value="' . $langcode . '" selected="selected">' . $name . '</option>', 'Correct language selected.');
// Ensure we can change the node language.
$edit = array(
'langcode[0][value]' => 'en',
);
$this->drupalPostForm($path, $edit, t('Save'));
$this->assertText(t('@title has been updated.', array('@title' => $node_title)));
// Verify that the creation message contains a link to a node.
$view_link = $this->xpath('//div[@class="messages"]//a[contains(@href, :href)]', array(':href' => 'node/' . $node->id()));
$this->assert(isset($view_link), 'The message area contains the link to the edited node');
$this->drupalLogout();
}
/**
* Test if a dir and lang tags exist in node's attributes.
*/
public function testContentTypeDirLang() {
$type = $this->drupalCreateContentType();
// User to add and remove language.
$admin_user = $this->drupalCreateUser(array('administer languages', 'administer content types', 'access administration pages'));
// User to create a node.
$web_user = $this->drupalCreateUser(array("create {$type->id()} content", "edit own {$type->id()} content"));
// Log in as admin.
$this->drupalLogin($admin_user);
// Install Arabic language.
$edit = array();
$edit['predefined_langcode'] = 'ar';
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));
// Install Spanish language.
$edit = array();
$edit['predefined_langcode'] = 'es';
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));
\Drupal::languageManager()->reset();
// Set the content type to use multilingual support.
$this->drupalGet("admin/structure/types/manage/{$type->id()}");
$edit = array(
'language_configuration[language_alterable]' => TRUE,
);
$this->drupalPostForm("admin/structure/types/manage/{$type->id()}", $edit, t('Save content type'));
$this->assertRaw(t('The content type %type has been updated.', array('%type' => $type->label())));
$this->drupalLogout();
// Log in as web user to add new node.
$this->drupalLogin($web_user);
// Create three nodes: English, Arabic and Spanish.
$nodes = array();
foreach (array('en', 'es', 'ar') as $langcode) {
$nodes[$langcode] = $this->drupalCreateNode(array(
'langcode' => $langcode,
'type' => $type->id(),
'promote' => NODE_PROMOTED,
));
}
// Check if English node does not have lang tag.
$this->drupalGet('node/' . $nodes['en']->id());
$element = $this->cssSelect('article.node[lang="en"]');
$this->assertTrue(empty($element), 'The lang tag has not been assigned to the English node.');
// Check if English node does not have dir tag.
$element = $this->cssSelect('article.node[dir="ltr"]');
$this->assertTrue(empty($element), 'The dir tag has not been assigned to the English node.');
// Check if Arabic node has lang="ar" & dir="rtl" tags.
$this->drupalGet('node/' . $nodes['ar']->id());
$element = $this->cssSelect('article.node[lang="ar"][dir="rtl"]');
$this->assertTrue(!empty($element), 'The lang and dir tags have been assigned correctly to the Arabic node.');
// Check if Spanish node has lang="es" tag.
$this->drupalGet('node/' . $nodes['es']->id());
$element = $this->cssSelect('article.node[lang="es"]');
$this->assertTrue(!empty($element), 'The lang tag has been assigned correctly to the Spanish node.');
// Check if Spanish node does not have dir="ltr" tag.
$element = $this->cssSelect('article.node[lang="es"][dir="ltr"]');
$this->assertTrue(empty($element), 'The dir tag has not been assigned to the Spanish node.');
}
}

View file

@ -16,7 +16,7 @@ class LocaleExportTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('locale');
public static $modules = ['locale'];
/**
* A user able to create languages and export translations.
@ -29,7 +29,7 @@ class LocaleExportTest extends WebTestBase {
protected function setUp() {
parent::setUp();
$this->adminUser = $this->drupalCreateUser(array('administer languages', 'translate interface', 'access administration pages'));
$this->adminUser = $this->drupalCreateUser(['administer languages', 'translate interface', 'access administration pages']);
$this->drupalLogin($this->adminUser);
// Copy test po files to the translations directory.
@ -45,16 +45,16 @@ class LocaleExportTest extends WebTestBase {
// This will also automatically add the 'fr' language.
$name = \Drupal::service('file_system')->tempnam('temporary://', "po_") . '.po';
file_put_contents($name, $this->getPoFile());
$this->drupalPostForm('admin/config/regional/translate/import', array(
$this->drupalPostForm('admin/config/regional/translate/import', [
'langcode' => 'fr',
'files[file]' => $name,
), t('Import'));
], t('Import'));
drupal_unlink($name);
// Get the French translations.
$this->drupalPostForm('admin/config/regional/translate/export', array(
$this->drupalPostForm('admin/config/regional/translate/export', [
'langcode' => 'fr',
), t('Export'));
], t('Export'));
// Ensure we have a translation file.
$this->assertRaw('# French translation of Drupal', 'Exported French translation file.');
@ -64,11 +64,11 @@ class LocaleExportTest extends WebTestBase {
// Import some more French translations which will be marked as customized.
$name = \Drupal::service('file_system')->tempnam('temporary://', "po2_") . '.po';
file_put_contents($name, $this->getCustomPoFile());
$this->drupalPostForm('admin/config/regional/translate/import', array(
$this->drupalPostForm('admin/config/regional/translate/import', [
'langcode' => 'fr',
'files[file]' => $name,
'customized' => 1,
), t('Import'));
], t('Import'));
drupal_unlink($name);
// Create string without translation in the locales_source table.
@ -79,12 +79,12 @@ class LocaleExportTest extends WebTestBase {
->save();
// Export only customized French translations.
$this->drupalPostForm('admin/config/regional/translate/export', array(
$this->drupalPostForm('admin/config/regional/translate/export', [
'langcode' => 'fr',
'content_options[not_customized]' => FALSE,
'content_options[customized]' => TRUE,
'content_options[not_translated]' => FALSE,
), t('Export'));
], t('Export'));
// Ensure we have a translation file.
$this->assertRaw('# French translation of Drupal', 'Exported French translation file with only customized strings.');
@ -94,12 +94,12 @@ class LocaleExportTest extends WebTestBase {
$this->assertNoRaw('msgid "February"', 'Untranslated string not present in exported file.');
// Export only untranslated French translations.
$this->drupalPostForm('admin/config/regional/translate/export', array(
$this->drupalPostForm('admin/config/regional/translate/export', [
'langcode' => 'fr',
'content_options[not_customized]' => FALSE,
'content_options[customized]' => FALSE,
'content_options[not_translated]' => TRUE,
), t('Export'));
], t('Export'));
// Ensure we have a translation file.
$this->assertRaw('# French translation of Drupal', 'Exported French translation file with only untranslated strings.');
@ -118,7 +118,7 @@ class LocaleExportTest extends WebTestBase {
// the locales_source table gets populated with something.
$this->drupalGet('admin/config/regional/language');
// Get the translation template file.
$this->drupalPostForm('admin/config/regional/translate/export', array(), t('Export'));
$this->drupalPostForm('admin/config/regional/translate/export', [], t('Export'));
// Ensure we have a translation file.
$this->assertRaw('# LANGUAGE translation of PROJECT', 'Exported translation template file.');
}

View file

@ -16,21 +16,21 @@ class LocaleFileSystemFormTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('system');
public static $modules = ['system'];
/**
* {@inheritdoc}
*/
protected function setUp(){
parent::setUp();
$account = $this->drupalCreateUser(array('administer site configuration'));
$account = $this->drupalCreateUser(['administer site configuration']);
$this->drupalLogin($account);
}
/**
* Tests translation directory settings on the file settings form.
*/
function testFileConfigurationPage() {
public function testFileConfigurationPage() {
// By default there should be no setting for the translation directory.
$this->drupalGet('admin/config/media/file-system');
$this->assertNoFieldByName('translation_path');
@ -44,9 +44,9 @@ class LocaleFileSystemFormTest extends WebTestBase {
// The setting should persist.
$translation_path = $this->publicFilesDirectory . '/translations_changed';
$fields = array(
$fields = [
'translation_path' => $translation_path
);
];
$this->drupalPostForm(NULL, $fields, t('Save configuration'));
$this->drupalGet('admin/config/media/file-system');
$this->assertFieldByName('translation_path', $translation_path);

View file

@ -17,7 +17,7 @@ class LocaleImportFunctionalTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('locale', 'dblog');
public static $modules = ['locale', 'dblog'];
/**
* A user able to create languages and import translations.
@ -44,8 +44,8 @@ class LocaleImportFunctionalTest extends WebTestBase {
file_unmanaged_copy(__DIR__ . '/../../tests/test.de.po', 'translations://', FILE_EXISTS_REPLACE);
file_unmanaged_copy(__DIR__ . '/../../tests/test.xx.po', 'translations://', FILE_EXISTS_REPLACE);
$this->adminUser = $this->drupalCreateUser(array('administer languages', 'translate interface', 'access administration pages'));
$this->adminUserAccessSiteReports = $this->drupalCreateUser(array('administer languages', 'translate interface', 'access administration pages', 'access site reports'));
$this->adminUser = $this->drupalCreateUser(['administer languages', 'translate interface', 'access administration pages']);
$this->adminUserAccessSiteReports = $this->drupalCreateUser(['administer languages', 'translate interface', 'access administration pages', 'access site reports']);
$this->drupalLogin($this->adminUser);
// Enable import of translations. By default this is disabled for automated
@ -60,15 +60,15 @@ class LocaleImportFunctionalTest extends WebTestBase {
*/
public function testStandalonePoFile() {
// Try importing a .po file.
$this->importPoFile($this->getPoFile(), array(
$this->importPoFile($this->getPoFile(), [
'langcode' => 'fr',
));
]);
$this->config('locale.settings');
// The import should automatically create the corresponding language.
$this->assertRaw(t('The language %language has been created.', array('%language' => 'French')), 'The language has been automatically created.');
$this->assertRaw(t('The language %language has been created.', ['%language' => 'French']), 'The language has been automatically created.');
// The import should have created 8 strings.
$this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', array('%number' => 8, '%update' => 0, '%delete' => 0)), 'The translation file was successfully imported.');
$this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', ['%number' => 8, '%update' => 0, '%delete' => 0]), 'The translation file was successfully imported.');
// This import should have saved plural forms to have 2 variants.
$locale_plurals = \Drupal::service('locale.plural.formula')->getNumberOfPlurals('fr');
@ -78,14 +78,14 @@ class LocaleImportFunctionalTest extends WebTestBase {
$this->assertUrl(\Drupal::url('locale.translate_page', [], ['absolute' => TRUE]), [], 'Correct page redirection.');
// Try importing a .po file with invalid tags.
$this->importPoFile($this->getBadPoFile(), array(
$this->importPoFile($this->getBadPoFile(), [
'langcode' => 'fr',
));
]);
// The import should have created 1 string and rejected 2.
$this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', array('%number' => 1, '%update' => 0, '%delete' => 0)), 'The translation file was successfully imported.');
$this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', ['%number' => 1, '%update' => 0, '%delete' => 0]), 'The translation file was successfully imported.');
$skip_message = \Drupal::translation()->formatPlural(2, 'One translation string was skipped because of disallowed or malformed HTML. <a href=":url">See the log</a> for details.', '@count translation strings were skipped because of disallowed or malformed HTML. See the log for details.', array(':url' => \Drupal::url('dblog.overview')));
$skip_message = \Drupal::translation()->formatPlural(2, 'One translation string was skipped because of disallowed or malformed HTML. <a href=":url">See the log</a> for details.', '@count translation strings were skipped because of disallowed or malformed HTML. See the log for details.', [':url' => \Drupal::url('dblog.overview')]);
$this->assertRaw($skip_message, 'Unsafe strings were skipped.');
// Repeat the process with a user that can access site reports, and this
@ -93,19 +93,19 @@ class LocaleImportFunctionalTest extends WebTestBase {
$this->drupalLogin($this->adminUserAccessSiteReports);
// Try importing a .po file with invalid tags.
$this->importPoFile($this->getBadPoFile(), array(
$this->importPoFile($this->getBadPoFile(), [
'langcode' => 'fr',
));
]);
$skip_message = \Drupal::translation()->formatPlural(2, 'One translation string was skipped because of disallowed or malformed HTML. <a href=":url">See the log</a> for details.', '@count translation strings were skipped because of disallowed or malformed HTML. <a href=":url">See the log</a> for details.', array(':url' => \Drupal::url('dblog.overview')));
$skip_message = \Drupal::translation()->formatPlural(2, 'One translation string was skipped because of disallowed or malformed HTML. <a href=":url">See the log</a> for details.', '@count translation strings were skipped because of disallowed or malformed HTML. <a href=":url">See the log</a> for details.', [':url' => \Drupal::url('dblog.overview')]);
$this->assertRaw($skip_message, 'Unsafe strings were skipped.');
// Check empty files import with a user that cannot access site reports..
$this->drupalLogin($this->adminUser);
// Try importing a zero byte sized .po file.
$this->importPoFile($this->getEmptyPoFile(), array(
$this->importPoFile($this->getEmptyPoFile(), [
'langcode' => 'fr',
));
]);
// The import should have created 0 string and rejected 0.
$this->assertRaw(t('One translation file could not be imported. See the log for details.'), 'The empty translation file import reported no translations imported.');
@ -113,35 +113,35 @@ class LocaleImportFunctionalTest extends WebTestBase {
// time the different warnings must contain links to the log.
$this->drupalLogin($this->adminUserAccessSiteReports);
// Try importing a zero byte sized .po file.
$this->importPoFile($this->getEmptyPoFile(), array(
$this->importPoFile($this->getEmptyPoFile(), [
'langcode' => 'fr',
));
]);
// The import should have created 0 string and rejected 0.
$this->assertRaw(t('One translation file could not be imported. <a href=":url">See the log</a> for details.', array(':url' => \Drupal::url('dblog.overview'))), 'The empty translation file import reported no translations imported.');
$this->assertRaw(t('One translation file could not be imported. <a href=":url">See the log</a> for details.', [':url' => \Drupal::url('dblog.overview')]), 'The empty translation file import reported no translations imported.');
// Try importing a .po file which doesn't exist.
$name = $this->randomMachineName(16);
$this->drupalPostForm('admin/config/regional/translate/import', array(
$this->drupalPostForm('admin/config/regional/translate/import', [
'langcode' => 'fr',
'files[file]' => $name,
), t('Import'));
], t('Import'));
$this->assertUrl(\Drupal::url('locale.translate_import', [], ['absolute' => TRUE]), [], 'Correct page redirection.');
$this->assertText(t('File to import not found.'), 'File to import not found message.');
// Try importing a .po file with overriding strings, and ensure existing
// strings are kept.
$this->importPoFile($this->getOverwritePoFile(), array(
$this->importPoFile($this->getOverwritePoFile(), [
'langcode' => 'fr',
));
]);
// The import should have created 1 string.
$this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', array('%number' => 1, '%update' => 0, '%delete' => 0)), 'The translation file was successfully imported.');
$this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', ['%number' => 1, '%update' => 0, '%delete' => 0]), 'The translation file was successfully imported.');
// Ensure string wasn't overwritten.
$search = array(
$search = [
'string' => 'Montag',
'langcode' => 'fr',
'translation' => 'translated',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$this->assertText(t('No strings available.'), 'String not overwritten by imported string.');
@ -151,19 +151,19 @@ class LocaleImportFunctionalTest extends WebTestBase {
// Try importing a .po file with overriding strings, and ensure existing
// strings are overwritten.
$this->importPoFile($this->getOverwritePoFile(), array(
$this->importPoFile($this->getOverwritePoFile(), [
'langcode' => 'fr',
'overwrite_options[not_customized]' => TRUE,
));
]);
// The import should have updated 2 strings.
$this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', array('%number' => 0, '%update' => 2, '%delete' => 0)), 'The translation file was successfully imported.');
$this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', ['%number' => 0, '%update' => 2, '%delete' => 0]), 'The translation file was successfully imported.');
// Ensure string was overwritten.
$search = array(
$search = [
'string' => 'Montag',
'langcode' => 'fr',
'translation' => 'translated',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$this->assertNoText(t('No strings available.'), 'String overwritten by imported string.');
// This import should have changed number of plural forms.
@ -171,54 +171,54 @@ class LocaleImportFunctionalTest extends WebTestBase {
$this->assertEqual(3, $locale_plurals, 'Plural numbers changed.');
// Importing a .po file and mark its strings as customized strings.
$this->importPoFile($this->getCustomPoFile(), array(
$this->importPoFile($this->getCustomPoFile(), [
'langcode' => 'fr',
'customized' => TRUE,
));
]);
// The import should have created 6 strings.
$this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', array('%number' => 6, '%update' => 0, '%delete' => 0)), 'The customized translation file was successfully imported.');
$this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', ['%number' => 6, '%update' => 0, '%delete' => 0]), 'The customized translation file was successfully imported.');
// The database should now contain 6 customized strings (two imported
// strings are not translated).
$count = db_query('SELECT COUNT(*) FROM {locales_target} WHERE customized = :custom', array(':custom' => 1))->fetchField();
$count = db_query('SELECT COUNT(*) FROM {locales_target} WHERE customized = :custom', [':custom' => 1])->fetchField();
$this->assertEqual($count, 6, 'Customized translations successfully imported.');
// Try importing a .po file with overriding strings, and ensure existing
// customized strings are kept.
$this->importPoFile($this->getCustomOverwritePoFile(), array(
$this->importPoFile($this->getCustomOverwritePoFile(), [
'langcode' => 'fr',
'overwrite_options[not_customized]' => TRUE,
'overwrite_options[customized]' => FALSE,
));
]);
// The import should have created 1 string.
$this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', array('%number' => 1, '%update' => 0, '%delete' => 0)), 'The customized translation file was successfully imported.');
$this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', ['%number' => 1, '%update' => 0, '%delete' => 0]), 'The customized translation file was successfully imported.');
// Ensure string wasn't overwritten.
$search = array(
$search = [
'string' => 'januari',
'langcode' => 'fr',
'translation' => 'translated',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$this->assertText(t('No strings available.'), 'Customized string not overwritten by imported string.');
// Try importing a .po file with overriding strings, and ensure existing
// customized strings are overwritten.
$this->importPoFile($this->getCustomOverwritePoFile(), array(
$this->importPoFile($this->getCustomOverwritePoFile(), [
'langcode' => 'fr',
'overwrite_options[not_customized]' => FALSE,
'overwrite_options[customized]' => TRUE,
));
]);
// The import should have updated 2 strings.
$this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', array('%number' => 0, '%update' => 2, '%delete' => 0)), 'The customized translation file was successfully imported.');
$this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', ['%number' => 0, '%update' => 2, '%delete' => 0]), 'The customized translation file was successfully imported.');
// Ensure string was overwritten.
$search = array(
$search = [
'string' => 'januari',
'langcode' => 'fr',
'translation' => 'translated',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$this->assertNoText(t('No strings available.'), 'Customized string overwritten by imported string.');
@ -229,14 +229,14 @@ class LocaleImportFunctionalTest extends WebTestBase {
*/
public function testLanguageContext() {
// Try importing a .po file.
$this->importPoFile($this->getPoFileWithContext(), array(
$this->importPoFile($this->getPoFileWithContext(), [
'langcode' => 'hr',
));
]);
// We cast the return value of t() to string so as to retrieve the
// translated value, rendered as a string.
$this->assertIdentical((string) t('May', array(), array('langcode' => 'hr', 'context' => 'Long month name')), 'Svibanj', 'Long month name context is working.');
$this->assertIdentical((string) t('May', array(), array('langcode' => 'hr')), 'Svi.', 'Default context is working.');
$this->assertIdentical((string) t('May', [], ['langcode' => 'hr', 'context' => 'Long month name']), 'Svibanj', 'Long month name context is working.');
$this->assertIdentical((string) t('May', [], ['langcode' => 'hr']), 'Svi.', 'Default context is working.');
}
/**
@ -246,26 +246,26 @@ class LocaleImportFunctionalTest extends WebTestBase {
$langcode = 'hu';
// Try importing a .po file.
$this->importPoFile($this->getPoFileWithMsgstr(), array(
$this->importPoFile($this->getPoFileWithMsgstr(), [
'langcode' => $langcode,
));
]);
$this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', array('%number' => 1, '%update' => 0, '%delete' => 0)), 'The translation file was successfully imported.');
$this->assertIdentical((string) t('Operations', array(), array('langcode' => $langcode)), 'Műveletek', 'String imported and translated.');
$this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', ['%number' => 1, '%update' => 0, '%delete' => 0]), 'The translation file was successfully imported.');
$this->assertIdentical((string) t('Operations', [], ['langcode' => $langcode]), 'Műveletek', 'String imported and translated.');
// Try importing a .po file.
$this->importPoFile($this->getPoFileWithEmptyMsgstr(), array(
$this->importPoFile($this->getPoFileWithEmptyMsgstr(), [
'langcode' => $langcode,
'overwrite_options[not_customized]' => TRUE,
));
$this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', array('%number' => 0, '%update' => 0, '%delete' => 1)), 'The translation file was successfully imported.');
]);
$this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.', ['%number' => 0, '%update' => 0, '%delete' => 1]), 'The translation file was successfully imported.');
$str = "Operations";
$search = array(
$search = [
'string' => $str,
'langcode' => $langcode,
'translation' => 'untranslated',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$this->assertText($str, 'Search found the string as untranslated.');
}
@ -276,27 +276,27 @@ class LocaleImportFunctionalTest extends WebTestBase {
public function testConfigPoFile() {
// Values for translations to assert. Config key, original string,
// translation and config property name.
$config_strings = array(
'system.maintenance' => array(
$config_strings = [
'system.maintenance' => [
'@site is currently under maintenance. We should be back shortly. Thank you for your patience.',
'@site karbantartás alatt áll. Rövidesen visszatérünk. Köszönjük a türelmet.',
'message',
),
'user.role.anonymous' => array(
],
'user.role.anonymous' => [
'Anonymous user',
'Névtelen felhasználó',
'label',
),
);
],
];
// Add custom language for testing.
$langcode = 'xx';
$edit = array(
$edit = [
'predefined_langcode' => 'custom',
'langcode' => $langcode,
'label' => $this->randomMachineName(16),
'direction' => LanguageInterface::DIRECTION_LTR,
);
];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
// Check for the source strings we are going to translate. Adding the
@ -304,24 +304,24 @@ class LocaleImportFunctionalTest extends WebTestBase {
// strings to interface translation executed.
$locale_storage = $this->container->get('locale.storage');
foreach ($config_strings as $config_string) {
$string = $locale_storage->findString(array('source' => $config_string[0], 'context' => '', 'type' => 'configuration'));
$string = $locale_storage->findString(['source' => $config_string[0], 'context' => '', 'type' => 'configuration']);
$this->assertTrue($string, 'Configuration strings have been created upon installation.');
}
// Import a .po file to translate.
$this->importPoFile($this->getPoFileWithConfig(), array(
$this->importPoFile($this->getPoFileWithConfig(), [
'langcode' => $langcode,
));
]);
// Translations got recorded in the interface translation system.
foreach ($config_strings as $config_string) {
$search = array(
$search = [
'string' => $config_string[0],
'langcode' => $langcode,
'translation' => 'all',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$this->assertText($config_string[1], format_string('Translation of @string found.', array('@string' => $config_string[0])));
$this->assertText($config_string[1], format_string('Translation of @string found.', ['@string' => $config_string[0]]));
}
// Test that translations got recorded in the config system.
@ -340,8 +340,8 @@ class LocaleImportFunctionalTest extends WebTestBase {
$langcode = 'de';
// Import a .po file to translate.
$this->importPoFile($this->getPoFileWithConfigDe(), array(
'langcode' => $langcode));
$this->importPoFile($this->getPoFileWithConfigDe(), [
'langcode' => $langcode]);
// Check that the 'Anonymous' string is translated.
$config = \Drupal::languageManager()->getLanguageConfigOverride($langcode, 'user.settings');
@ -353,7 +353,7 @@ class LocaleImportFunctionalTest extends WebTestBase {
*/
public function testCreatedLanguageTranslation() {
// Import a .po file to add de language.
$this->importPoFile($this->getPoFileWithConfigDe(), array('langcode' => 'de'));
$this->importPoFile($this->getPoFileWithConfigDe(), ['langcode' => 'de']);
// Get the language.entity.de label and check it's been translated.
$override = \Drupal::languageManager()->getLanguageConfigOverride('de', 'language.entity.de');
@ -368,7 +368,7 @@ class LocaleImportFunctionalTest extends WebTestBase {
* @param array $options
* (optional) Additional options to pass to the translation import form.
*/
public function importPoFile($contents, array $options = array()) {
public function importPoFile($contents, array $options = []) {
$name = \Drupal::service('file_system')->tempnam('temporary://', "po_") . '.po';
file_put_contents($name, $contents);
$options['files[file]'] = $name;

View file

@ -18,7 +18,7 @@ class LocaleJavascriptTranslationTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('locale', 'locale_test');
public static $modules = ['locale', 'locale_test'];
public function testFileParsing() {
$filename = __DIR__ . '/../../tests/locale_test.js';
@ -29,19 +29,19 @@ class LocaleJavascriptTranslationTest extends WebTestBase {
// Get all of the source strings that were found.
$strings = $this->container
->get('locale.storage')
->getStrings(array(
->getStrings([
'type' => 'javascript',
'name' => $filename,
));
]);
$source_strings = array();
$source_strings = [];
foreach ($strings as $string) {
$source_strings[$string->source] = $string->context;
}
$etx = LOCALE_PLURAL_DELIMITER;
// List of all strings that should be in the file.
$test_strings = array(
$test_strings = [
'Standard Call t' => '',
'Whitespace Call t' => '',
@ -73,11 +73,11 @@ class LocaleJavascriptTranslationTest extends WebTestBase {
"Context Unquoted plural{$etx}Context Unquoted @count plural" => 'Context string unquoted',
"Context Single Quoted plural{$etx}Context Single Quoted @count plural" => 'Context string single quoted',
"Context Double Quoted plural{$etx}Context Double Quoted @count plural" => 'Context string double quoted',
);
];
// Assert that all strings were found properly.
foreach ($test_strings as $str => $context) {
$args = array('%source' => $str, '%context' => $context);
$args = ['%source' => $str, '%context' => $context];
// Make sure that the string was found in the file.
$this->assertTrue(isset($source_strings[$str]), SafeMarkup::format('Found source string: %source', $args));
@ -95,7 +95,7 @@ class LocaleJavascriptTranslationTest extends WebTestBase {
*/
public function testLocaleTranslationJsDependencies() {
// User to add and remove language.
$admin_user = $this->drupalCreateUser(array('administer languages', 'access administration pages', 'translate interface'));
$admin_user = $this->drupalCreateUser(['administer languages', 'access administration pages', 'translate interface']);
// Add custom language.
$this->drupalLogin($admin_user);
@ -105,16 +105,16 @@ class LocaleJavascriptTranslationTest extends WebTestBase {
$name = $this->randomMachineName(16);
// The domain prefix.
$prefix = $langcode;
$edit = array(
$edit = [
'predefined_langcode' => 'custom',
'langcode' => $langcode,
'label' => $name,
'direction' => LanguageInterface::DIRECTION_LTR,
);
];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
// Set path prefix.
$edit = array("prefix[$langcode]" => $prefix);
$edit = ["prefix[$langcode]" => $prefix];
$this->drupalPostForm('admin/config/regional/language/detection/url', $edit, t('Save configuration'));
// This forces locale.admin.js string sources to be imported, which contains
@ -123,11 +123,11 @@ class LocaleJavascriptTranslationTest extends WebTestBase {
// Translate a string in locale.admin.js to our new language.
$strings = \Drupal::service('locale.storage')
->getStrings(array(
->getStrings([
'source' => 'Show description',
'type' => 'javascript',
'name' => 'core/modules/locale/locale.admin.js',
));
]);
$string = $strings[0];
$this->drupalPostForm(NULL, ['string' => 'Show description'], t('Filter'));

View file

@ -19,7 +19,7 @@ class LocaleLibraryAlterTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('locale');
public static $modules = ['locale'];
/**
* Verifies that the datepicker can be localized.

View file

@ -1,58 +0,0 @@
<?php
namespace Drupal\locale\Tests;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\simpletest\WebTestBase;
/**
* Tests LocaleLookup.
*
* @group locale
*/
class LocaleLocaleLookupTest extends WebTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('locale', 'locale_test');
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// Change the language default object to different values.
ConfigurableLanguage::createFromLangcode('fr')->save();
$this->config('system.site')->set('default_langcode', 'fr')->save();
$this->drupalLogin($this->rootUser);
}
/**
* Tests that there are no circular dependencies.
*/
public function testCircularDependency() {
// Ensure that we can enable early_translation_test on a non-english site.
$this->drupalPostForm('admin/modules', array('modules[Testing][early_translation_test][enable]' => TRUE), t('Install'));
$this->assertResponse(200);
}
/**
* Test language fallback defaults.
*/
public function testLanguageFallbackDefaults() {
$this->drupalGet('');
// Ensure state of fallback languages persisted by
// locale_test_language_fallback_candidates_locale_lookup_alter() is empty.
$this->assertEqual(\Drupal::state()->get('locale.test_language_fallback_candidates_locale_lookup_alter_candidates'), array());
// Make sure there is enough information provided for alter hooks.
$context = \Drupal::state()->get('locale.test_language_fallback_candidates_locale_lookup_alter_context');
$this->assertEqual($context['langcode'], 'fr');
$this->assertEqual($context['operation'], 'locale_lookup');
}
}

View file

@ -1,151 +0,0 @@
<?php
namespace Drupal\locale\Tests;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Url;
use Drupal\simpletest\WebTestBase;
/**
* Tests you can configure a language for individual URL aliases.
*
* @group locale
*/
class LocalePathTest extends WebTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('node', 'locale', 'path', 'views');
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page'));
$this->config('system.site')->set('page.front', '/node')->save();
}
/**
* Test if a language can be associated with a path alias.
*/
public function testPathLanguageConfiguration() {
// User to add and remove language.
$admin_user = $this->drupalCreateUser(array('administer languages', 'create page content', 'administer url aliases', 'create url aliases', 'access administration pages', 'access content overview'));
// Add custom language.
$this->drupalLogin($admin_user);
// Code for the language.
$langcode = 'xx';
// The English name for the language.
$name = $this->randomMachineName(16);
// The domain prefix.
$prefix = $langcode;
$edit = array(
'predefined_langcode' => 'custom',
'langcode' => $langcode,
'label' => $name,
'direction' => LanguageInterface::DIRECTION_LTR,
);
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
// Set path prefix.
$edit = array("prefix[$langcode]" => $prefix);
$this->drupalPostForm('admin/config/regional/language/detection/url', $edit, t('Save configuration'));
// Check that the "xx" front page is readily available because path prefix
// negotiation is pre-configured.
$this->drupalGet($prefix);
$this->assertText(t('Welcome to Drupal'), 'The "xx" front page is readibly available.');
// Create a node.
$node = $this->drupalCreateNode(array('type' => 'page'));
// Create a path alias in default language (English).
$path = 'admin/config/search/path/add';
$english_path = $this->randomMachineName(8);
$edit = array(
'source' => '/node/' . $node->id(),
'alias' => '/' . $english_path,
'langcode' => 'en',
);
$this->drupalPostForm($path, $edit, t('Save'));
// Create a path alias in new custom language.
$custom_language_path = $this->randomMachineName(8);
$edit = array(
'source' => '/node/' . $node->id(),
'alias' => '/' . $custom_language_path,
'langcode' => $langcode,
);
$this->drupalPostForm($path, $edit, t('Save'));
// Confirm English language path alias works.
$this->drupalGet($english_path);
$this->assertText($node->label(), 'English alias works.');
// Confirm custom language path alias works.
$this->drupalGet($prefix . '/' . $custom_language_path);
$this->assertText($node->label(), 'Custom language alias works.');
// Create a custom path.
$custom_path = $this->randomMachineName(8);
// Check priority of language for alias by source path.
$edit = array(
'source' => '/node/' . $node->id(),
'alias' => '/' . $custom_path,
'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
);
$this->container->get('path.alias_storage')->save($edit['source'], $edit['alias'], $edit['langcode']);
$lookup_path = $this->container->get('path.alias_manager')->getAliasByPath('/node/' . $node->id(), 'en');
$this->assertEqual('/' . $english_path, $lookup_path, 'English language alias has priority.');
// Same check for language 'xx'.
$lookup_path = $this->container->get('path.alias_manager')->getAliasByPath('/node/' . $node->id(), $prefix);
$this->assertEqual('/' . $custom_language_path, $lookup_path, 'Custom language alias has priority.');
$this->container->get('path.alias_storage')->delete($edit);
// Create language nodes to check priority of aliases.
$first_node = $this->drupalCreateNode(array('type' => 'page', 'promote' => 1, 'langcode' => 'en'));
$second_node = $this->drupalCreateNode(array('type' => 'page', 'promote' => 1, 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED));
// Assign a custom path alias to the first node with the English language.
$edit = array(
'source' => '/node/' . $first_node->id(),
'alias' => '/' . $custom_path,
'langcode' => $first_node->language()->getId(),
);
$this->container->get('path.alias_storage')->save($edit['source'], $edit['alias'], $edit['langcode']);
// Assign a custom path alias to second node with
// LanguageInterface::LANGCODE_NOT_SPECIFIED.
$edit = array(
'source' => '/node/' . $second_node->id(),
'alias' => '/' . $custom_path,
'langcode' => $second_node->language()->getId(),
);
$this->container->get('path.alias_storage')->save($edit['source'], $edit['alias'], $edit['langcode']);
// Test that both node titles link to our path alias.
$this->drupalGet('admin/content');
$custom_path_url = Url::fromUserInput('/' . $custom_path)->toString();
$elements = $this->xpath('//a[@href=:href and normalize-space(text())=:title]', array(':href' => $custom_path_url, ':title' => $first_node->label()));
$this->assertTrue(!empty($elements), 'First node links to the path alias.');
$elements = $this->xpath('//a[@href=:href and normalize-space(text())=:title]', array(':href' => $custom_path_url, ':title' => $second_node->label()));
$this->assertTrue(!empty($elements), 'Second node links to the path alias.');
// Confirm that the custom path leads to the first node.
$this->drupalGet($custom_path);
$this->assertText($first_node->label(), 'Custom alias returns first node.');
// Confirm that the custom path with prefix leads to the second node.
$this->drupalGet($prefix . '/' . $custom_path);
$this->assertText($second_node->label(), 'Custom alias with prefix returns second node.');
}
}

View file

@ -24,7 +24,7 @@ class LocalePluralFormatTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('locale');
public static $modules = ['locale'];
/**
* {@inheritdoc}
@ -32,7 +32,7 @@ class LocalePluralFormatTest extends WebTestBase {
protected function setUp() {
parent::setUp();
$this->adminUser = $this->drupalCreateUser(array('administer languages', 'translate interface', 'access administration pages'));
$this->adminUser = $this->drupalCreateUser(['administer languages', 'translate interface', 'access administration pages']);
$this->drupalLogin($this->adminUser);
}
@ -43,23 +43,23 @@ class LocalePluralFormatTest extends WebTestBase {
public function testGetPluralFormat() {
// Import some .po files with formulas to set up the environment.
// These will also add the languages to the system.
$this->importPoFile($this->getPoFileWithSimplePlural(), array(
$this->importPoFile($this->getPoFileWithSimplePlural(), [
'langcode' => 'fr',
));
$this->importPoFile($this->getPoFileWithComplexPlural(), array(
]);
$this->importPoFile($this->getPoFileWithComplexPlural(), [
'langcode' => 'hr',
));
]);
// Attempt to import some broken .po files as well to prove that these
// will not overwrite the proper plural formula imported above.
$this->importPoFile($this->getPoFileWithMissingPlural(), array(
$this->importPoFile($this->getPoFileWithMissingPlural(), [
'langcode' => 'fr',
'overwrite_options[not_customized]' => TRUE,
));
$this->importPoFile($this->getPoFileWithBrokenPlural(), array(
]);
$this->importPoFile($this->getPoFileWithBrokenPlural(), [
'langcode' => 'hr',
'overwrite_options[not_customized]' => TRUE,
));
]);
// Reset static caches from locale_get_plural() to ensure we get fresh data.
drupal_static_reset('locale_get_plural');
@ -67,49 +67,49 @@ class LocalePluralFormatTest extends WebTestBase {
drupal_static_reset('locale');
// Expected plural translation strings for each plural index.
$plural_strings = array(
$plural_strings = [
// English is not imported in this case, so we assume built-in text
// and formulas.
'en' => array(
'en' => [
0 => '1 hour',
1 => '@count hours',
),
'fr' => array(
],
'fr' => [
0 => '@count heure',
1 => '@count heures',
),
'hr' => array(
],
'hr' => [
0 => '@count sat',
1 => '@count sata',
2 => '@count sati',
),
],
// Hungarian is not imported, so it should assume the same text as
// English, but it will always pick the plural form as per the built-in
// logic, so only index -1 is relevant with the plural value.
'hu' => array(
'hu' => [
0 => '1 hour',
-1 => '@count hours',
),
);
],
];
// Expected plural indexes precomputed base on the plural formulas with
// given $count value.
$plural_tests = array(
'en' => array(
$plural_tests = [
'en' => [
1 => 0,
0 => 1,
5 => 1,
123 => 1,
235 => 1,
),
'fr' => array(
],
'fr' => [
1 => 0,
0 => 0,
5 => 1,
123 => 1,
235 => 1,
),
'hr' => array(
],
'hr' => [
1 => 0,
21 => 0,
0 => 2,
@ -117,13 +117,13 @@ class LocalePluralFormatTest extends WebTestBase {
8 => 2,
123 => 1,
235 => 2,
),
'hu' => array(
],
'hu' => [
1 => -1,
21 => -1,
0 => -1,
),
);
],
];
foreach ($plural_tests as $langcode => $tests) {
foreach ($tests as $count => $expected_plural_index) {
@ -133,14 +133,14 @@ class LocalePluralFormatTest extends WebTestBase {
// expected index as per the logic for translation lookups.
$expected_plural_index = ($count == 1) ? 0 : $expected_plural_index;
$expected_plural_string = str_replace('@count', $count, $plural_strings[$langcode][$expected_plural_index]);
$this->assertIdentical(\Drupal::translation()->formatPlural($count, '1 hour', '@count hours', array(), array('langcode' => $langcode))->render(), $expected_plural_string, 'Plural translation of 1 hours / @count hours for count ' . $count . ' in ' . $langcode . ' is ' . $expected_plural_string);
$this->assertIdentical(\Drupal::translation()->formatPlural($count, '1 hour', '@count hours', [], ['langcode' => $langcode])->render(), $expected_plural_string, 'Plural translation of 1 hours / @count hours for count ' . $count . ' in ' . $langcode . ' is ' . $expected_plural_string);
// DO NOT use translation to pass translated strings into
// PluralTranslatableMarkup::createFromTranslatedString() this way. It
// is designed to be used with *already* translated text like settings
// from configuration. We use PHP translation here just because we have
// the expected result data in that format.
$translated_string = \Drupal::translation()->translate('1 hour' . PluralTranslatableMarkup::DELIMITER . '@count hours', array(), array('langcode' => $langcode));
$plural = PluralTranslatableMarkup::createFromTranslatedString($count, $translated_string, array(), array('langcode' => $langcode));
$translated_string = \Drupal::translation()->translate('1 hour' . PluralTranslatableMarkup::DELIMITER . '@count hours', [], ['langcode' => $langcode]);
$plural = PluralTranslatableMarkup::createFromTranslatedString($count, $translated_string, [], ['langcode' => $langcode]);
$this->assertIdentical($plural->render(), $expected_plural_string);
}
}
@ -153,9 +153,9 @@ class LocalePluralFormatTest extends WebTestBase {
// Import some .po files with formulas to set up the environment.
// These will also add the languages to the system.
$this->importPoFile($this->getPoFileWithSimplePlural(), array(
$this->importPoFile($this->getPoFileWithSimplePlural(), [
'langcode' => 'fr',
));
]);
// Set French as the site default language.
$this->config('system.site')->set('default_langcode', 'fr')->save();
@ -170,12 +170,12 @@ class LocalePluralFormatTest extends WebTestBase {
$this->assertText("seconde", "'Member for' text is translated.");
$path = 'admin/config/regional/translate/';
$search = array(
$search = [
'langcode' => 'fr',
// Limit to only translated strings to ensure that database ordering does
// not break the test.
'translation' => 'translated',
);
];
$this->drupalPostForm($path, $search, t('Filter'));
// Plural values for the langcode fr.
$this->assertText('@count seconde');
@ -185,20 +185,20 @@ class LocalePluralFormatTest extends WebTestBase {
// langcode here because the language will be English by default and will
// not save our source string for performance optimization if we do not ask
// specifically for a language.
\Drupal::translation()->formatPlural(1, '1 second', '@count seconds', array(), array('langcode' => 'fr'))->render();
$lid = db_query("SELECT lid FROM {locales_source} WHERE source = :source AND context = ''", array(':source' => "1 second" . LOCALE_PLURAL_DELIMITER . "@count seconds"))->fetchField();
\Drupal::translation()->formatPlural(1, '1 second', '@count seconds', [], ['langcode' => 'fr'])->render();
$lid = db_query("SELECT lid FROM {locales_source} WHERE source = :source AND context = ''", [':source' => "1 second" . LOCALE_PLURAL_DELIMITER . "@count seconds"])->fetchField();
// Look up editing page for this plural string and check fields.
$search = array(
$search = [
'string' => '1 second',
'langcode' => 'fr',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
// Save complete translations for the string in langcode fr.
$edit = array(
$edit = [
"strings[$lid][translations][0]" => '1 seconde updated',
"strings[$lid][translations][1]" => '@count secondes updated',
);
];
$this->drupalPostForm($path, $edit, t('Save translations'));
// User interface input for translating seconds should not be duplicated
@ -218,17 +218,17 @@ class LocalePluralFormatTest extends WebTestBase {
public function testPluralEditExport() {
// Import some .po files with formulas to set up the environment.
// These will also add the languages to the system.
$this->importPoFile($this->getPoFileWithSimplePlural(), array(
$this->importPoFile($this->getPoFileWithSimplePlural(), [
'langcode' => 'fr',
));
$this->importPoFile($this->getPoFileWithComplexPlural(), array(
]);
$this->importPoFile($this->getPoFileWithComplexPlural(), [
'langcode' => 'hr',
));
]);
// Get the French translations.
$this->drupalPostForm('admin/config/regional/translate/export', array(
$this->drupalPostForm('admin/config/regional/translate/export', [
'langcode' => 'fr',
), t('Export'));
], t('Export'));
// Ensure we have a translation file.
$this->assertRaw('# French translation of Drupal', 'Exported French translation file.');
// Ensure our imported translations exist in the file.
@ -237,9 +237,9 @@ class LocalePluralFormatTest extends WebTestBase {
$this->assertRaw("msgid \"1 hour\"\nmsgid_plural \"@count hours\"\nmsgstr[0] \"@count heure\"\nmsgstr[1] \"@count heures\"", 'Plural translations exported properly.');
// Get the Croatian translations.
$this->drupalPostForm('admin/config/regional/translate/export', array(
$this->drupalPostForm('admin/config/regional/translate/export', [
'langcode' => 'hr',
), t('Export'));
], t('Export'));
// Ensure we have a translation file.
$this->assertRaw('# Croatian translation of Drupal', 'Exported Croatian translation file.');
// Ensure our imported translations exist in the file.
@ -254,9 +254,9 @@ class LocalePluralFormatTest extends WebTestBase {
// Look up editing page for this plural string and check fields.
$path = 'admin/config/regional/translate/';
$search = array(
$search = [
'langcode' => 'hr',
);
];
$this->drupalPostForm($path, $search, t('Filter'));
// Labels for plural editing elements.
$this->assertText('Singular form');
@ -270,15 +270,15 @@ class LocalePluralFormatTest extends WebTestBase {
$this->assertText('@count sati');
// Edit langcode hr translations and see if that took effect.
$lid = db_query("SELECT lid FROM {locales_source} WHERE source = :source AND context = ''", array(':source' => "1 hour" . LOCALE_PLURAL_DELIMITER . "@count hours"))->fetchField();
$edit = array(
$lid = db_query("SELECT lid FROM {locales_source} WHERE source = :source AND context = ''", [':source' => "1 hour" . LOCALE_PLURAL_DELIMITER . "@count hours"])->fetchField();
$edit = [
"strings[$lid][translations][1]" => '@count sata edited',
);
];
$this->drupalPostForm($path, $edit, t('Save translations'));
$search = array(
$search = [
'langcode' => 'fr',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
// Plural values for the langcode fr.
$this->assertText('@count heure');
@ -286,57 +286,57 @@ class LocalePluralFormatTest extends WebTestBase {
$this->assertNoText('2. plural form');
// Edit langcode fr translations and see if that took effect.
$edit = array(
$edit = [
"strings[$lid][translations][0]" => '@count heure edited',
);
];
$this->drupalPostForm($path, $edit, t('Save translations'));
// Inject a plural source string to the database. We need to use a specific
// langcode here because the language will be English by default and will
// not save our source string for performance optimization if we do not ask
// specifically for a language.
\Drupal::translation()->formatPlural(1, '1 day', '@count days', array(), array('langcode' => 'fr'))->render();
$lid = db_query("SELECT lid FROM {locales_source} WHERE source = :source AND context = ''", array(':source' => "1 day" . LOCALE_PLURAL_DELIMITER . "@count days"))->fetchField();
\Drupal::translation()->formatPlural(1, '1 day', '@count days', [], ['langcode' => 'fr'])->render();
$lid = db_query("SELECT lid FROM {locales_source} WHERE source = :source AND context = ''", [':source' => "1 day" . LOCALE_PLURAL_DELIMITER . "@count days"])->fetchField();
// Look up editing page for this plural string and check fields.
$search = array(
$search = [
'string' => '1 day',
'langcode' => 'fr',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
// Save complete translations for the string in langcode fr.
$edit = array(
$edit = [
"strings[$lid][translations][0]" => '1 jour',
"strings[$lid][translations][1]" => '@count jours',
);
];
$this->drupalPostForm($path, $edit, t('Save translations'));
// Save complete translations for the string in langcode hr.
$search = array(
$search = [
'string' => '1 day',
'langcode' => 'hr',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$edit = array(
$edit = [
"strings[$lid][translations][0]" => '@count dan',
"strings[$lid][translations][1]" => '@count dana',
"strings[$lid][translations][2]" => '@count dana',
);
];
$this->drupalPostForm($path, $edit, t('Save translations'));
// Get the French translations.
$this->drupalPostForm('admin/config/regional/translate/export', array(
$this->drupalPostForm('admin/config/regional/translate/export', [
'langcode' => 'fr',
), t('Export'));
], t('Export'));
// Check for plural export specifically.
$this->assertRaw("msgid \"1 hour\"\nmsgid_plural \"@count hours\"\nmsgstr[0] \"@count heure edited\"\nmsgstr[1] \"@count heures\"", 'Edited French plural translations for hours exported properly.');
$this->assertRaw("msgid \"1 day\"\nmsgid_plural \"@count days\"\nmsgstr[0] \"1 jour\"\nmsgstr[1] \"@count jours\"", 'Added French plural translations for days exported properly.');
// Get the Croatian translations.
$this->drupalPostForm('admin/config/regional/translate/export', array(
$this->drupalPostForm('admin/config/regional/translate/export', [
'langcode' => 'hr',
), t('Export'));
], t('Export'));
// Check for plural export specifically.
$this->assertRaw("msgid \"1 hour\"\nmsgid_plural \"@count hours\"\nmsgstr[0] \"@count sat\"\nmsgstr[1] \"@count sata edited\"\nmsgstr[2] \"@count sati\"", 'Edited Croatian plural translations exported properly.');
$this->assertRaw("msgid \"1 day\"\nmsgid_plural \"@count days\"\nmsgstr[0] \"@count dan\"\nmsgstr[1] \"@count dana\"\nmsgstr[2] \"@count dana\"", 'Added Croatian plural translations exported properly.');
@ -350,7 +350,7 @@ class LocalePluralFormatTest extends WebTestBase {
* @param array $options
* Additional options to pass to the translation import form.
*/
public function importPoFile($contents, array $options = array()) {
public function importPoFile($contents, array $options = []) {
$name = \Drupal::service('file_system')->tempnam('temporary://', "po_") . '.po';
file_put_contents($name, $contents);
$options['files[file]'] = $name;

View file

@ -1,205 +0,0 @@
<?php
namespace Drupal\locale\Tests;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\simpletest\WebTestBase;
/**
* Tests the locale string storage, string objects and data API.
*
* @group locale
*/
class LocaleStringTest extends WebTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('locale');
/**
* The locale storage.
*
* @var \Drupal\locale\StringStorageInterface
*/
protected $storage;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// Add a default locale storage for all these tests.
$this->storage = $this->container->get('locale.storage');
// Create two languages: Spanish and German.
foreach (array('es', 'de') as $langcode) {
ConfigurableLanguage::createFromLangcode($langcode)->save();
}
}
/**
* Test CRUD API.
*/
public function testStringCRUDAPI() {
// Create source string.
$source = $this->buildSourceString();
$source->save();
$this->assertTrue($source->lid, format_string('Successfully created string %string', array('%string' => $source->source)));
// Load strings by lid and source.
$string1 = $this->storage->findString(array('lid' => $source->lid));
$this->assertEqual($source, $string1, 'Successfully retrieved string by identifier.');
$string2 = $this->storage->findString(array('source' => $source->source, 'context' => $source->context));
$this->assertEqual($source, $string2, 'Successfully retrieved string by source and context.');
$string3 = $this->storage->findString(array('source' => $source->source, 'context' => ''));
$this->assertFalse($string3, 'Cannot retrieve string with wrong context.');
// Check version handling and updating.
$this->assertEqual($source->version, 'none', 'String originally created without version.');
$string = $this->storage->findTranslation(array('lid' => $source->lid));
$this->assertEqual($string->version, \Drupal::VERSION, 'Checked and updated string version to Drupal version.');
// Create translation and find it by lid and source.
$langcode = 'es';
$translation = $this->createTranslation($source, $langcode);
$this->assertEqual($translation->customized, LOCALE_NOT_CUSTOMIZED, 'Translation created as not customized by default.');
$string1 = $this->storage->findTranslation(array('language' => $langcode, 'lid' => $source->lid));
$this->assertEqual($string1->translation, $translation->translation, 'Successfully loaded translation by string identifier.');
$string2 = $this->storage->findTranslation(array('language' => $langcode, 'source' => $source->source, 'context' => $source->context));
$this->assertEqual($string2->translation, $translation->translation, 'Successfully loaded translation by source and context.');
$translation
->setCustomized()
->save();
$translation = $this->storage->findTranslation(array('language' => $langcode, 'lid' => $source->lid));
$this->assertEqual($translation->customized, LOCALE_CUSTOMIZED, 'Translation successfully marked as customized.');
// Delete translation.
$translation->delete();
$deleted = $this->storage->findTranslation(array('language' => $langcode, 'lid' => $source->lid));
$this->assertFalse(isset($deleted->translation), 'Successfully deleted translation string.');
// Create some translations and then delete string and all of its
// translations.
$lid = $source->lid;
$this->createAllTranslations($source);
$search = $this->storage->getTranslations(array('lid' => $source->lid));
$this->assertEqual(count($search), 3, 'Created and retrieved all translations for our source string.');
$source->delete();
$string = $this->storage->findString(array('lid' => $lid));
$this->assertFalse($string, 'Successfully deleted source string.');
$deleted = $search = $this->storage->getTranslations(array('lid' => $lid));
$this->assertFalse($deleted, 'Successfully deleted all translation strings.');
// Tests that locations of different types and arbitrary lengths can be
// added to a source string. Too long locations will be cut off.
$source_string = $this->buildSourceString();
$source_string->addLocation('javascript', $this->randomString(8));
$source_string->addLocation('configuration', $this->randomString(50));
$source_string->addLocation('code', $this->randomString(100));
$source_string->addLocation('path', $location = $this->randomString(300));
$source_string->save();
$rows = db_query('SELECT * FROM {locales_location} WHERE sid = :sid', array(':sid' => $source_string->lid))->fetchAllAssoc('type');
$this->assertEqual(count($rows), 4, '4 source locations have been persisted.');
$this->assertEqual($rows['path']->name, substr($location, 0, 255), 'Too long location has been limited to 255 characters.');
}
/**
* Test Search API loading multiple objects.
*/
public function testStringSearchAPI() {
$language_count = 3;
// Strings 1 and 2 will have some common prefix.
// Source 1 will have all translations, not customized.
// Source 2 will have all translations, customized.
// Source 3 will have no translations.
$prefix = $this->randomMachineName(100);
$source1 = $this->buildSourceString(array('source' => $prefix . $this->randomMachineName(100)))->save();
$source2 = $this->buildSourceString(array('source' => $prefix . $this->randomMachineName(100)))->save();
$source3 = $this->buildSourceString()->save();
// Load all source strings.
$strings = $this->storage->getStrings(array());
$this->assertEqual(count($strings), 3, 'Found 3 source strings in the database.');
// Load all source strings matching a given string.
$filter_options['filters'] = array('source' => $prefix);
$strings = $this->storage->getStrings(array(), $filter_options);
$this->assertEqual(count($strings), 2, 'Found 2 strings using some string filter.');
// Not customized translations.
$translate1 = $this->createAllTranslations($source1);
// Customized translations.
$this->createAllTranslations($source2, array('customized' => LOCALE_CUSTOMIZED));
// Try quick search function with different field combinations.
$langcode = 'es';
$found = $this->storage->findTranslation(array('language' => $langcode, 'source' => $source1->source, 'context' => $source1->context));
$this->assertTrue($found && isset($found->language) && isset($found->translation) && !$found->isNew(), 'Translation found searching by source and context.');
$this->assertEqual($found->translation, $translate1[$langcode]->translation, 'Found the right translation.');
// Now try a translation not found.
$found = $this->storage->findTranslation(array('language' => $langcode, 'source' => $source3->source, 'context' => $source3->context));
$this->assertTrue($found && $found->lid == $source3->lid && !isset($found->translation) && $found->isNew(), 'Translation not found but source string found.');
// Load all translations. For next queries we'll be loading only translated
// strings.
$translations = $this->storage->getTranslations(array('translated' => TRUE));
$this->assertEqual(count($translations), 2 * $language_count, 'Created and retrieved all translations for source strings.');
// Load all customized translations.
$translations = $this->storage->getTranslations(array('customized' => LOCALE_CUSTOMIZED, 'translated' => TRUE));
$this->assertEqual(count($translations), $language_count, 'Retrieved all customized translations for source strings.');
// Load all Spanish customized translations.
$translations = $this->storage->getTranslations(array('language' => 'es', 'customized' => LOCALE_CUSTOMIZED, 'translated' => TRUE));
$this->assertEqual(count($translations), 1, 'Found only Spanish and customized translations.');
// Load all source strings without translation (1).
$translations = $this->storage->getStrings(array('translated' => FALSE));
$this->assertEqual(count($translations), 1, 'Found 1 source string without translations.');
// Load Spanish translations using string filter.
$filter_options['filters'] = array('source' => $prefix);
$translations = $this->storage->getTranslations(array('language' => 'es'), $filter_options);
$this->assertEqual(count($translations), 2, 'Found 2 translations using some string filter.');
}
/**
* Creates random source string object.
*
* @return \Drupal\locale\StringInterface
* A locale string.
*/
public function buildSourceString($values = array()) {
return $this->storage->createString($values += array(
'source' => $this->randomMachineName(100),
'context' => $this->randomMachineName(20),
));
}
/**
* Creates translations for source string and all languages.
*/
public function createAllTranslations($source, $values = array()) {
$list = array();
/* @var $language_manager \Drupal\Core\Language\LanguageManagerInterface */
$language_manager = $this->container->get('language_manager');
foreach ($language_manager->getLanguages() as $language) {
$list[$language->getId()] = $this->createTranslation($source, $language->getId(), $values);
}
return $list;
}
/**
* Creates single translation for source string.
*/
public function createTranslation($source, $langcode, $values = array()) {
return $this->storage->createTranslation($values + array(
'lid' => $source->lid,
'language' => $langcode,
'translation' => $this->randomMachineName(100),
))->save();
}
}

View file

@ -23,14 +23,14 @@ class LocaleTranslateStringTourTest extends TourTestBase {
*
* @var array
*/
public static $modules = array('locale', 'tour');
public static $modules = ['locale', 'tour'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->adminUser = $this->drupalCreateUser(array('translate interface', 'access tour', 'administer languages'));
$this->adminUser = $this->drupalCreateUser(['translate interface', 'access tour', 'administer languages']);
$this->drupalLogin($this->adminUser);
}
@ -39,7 +39,7 @@ class LocaleTranslateStringTourTest extends TourTestBase {
*/
public function testTranslateStringTourTips() {
// Add another language so there are no missing form items.
$edit = array();
$edit = [];
$edit['predefined_langcode'] = 'es';
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));

View file

@ -1,91 +0,0 @@
<?php
namespace Drupal\locale\Tests;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\simpletest\WebTestBase;
/**
* Adds and configures languages to check field schema definition.
*
* @group locale
*/
class LocaleTranslatedSchemaDefinitionTest extends WebTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('language', 'locale', 'node');
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
ConfigurableLanguage::createFromLangcode('fr')->save();
$this->config('system.site')->set('default_langcode', 'fr')->save();
// Make sure new entity type definitions are processed.
\Drupal::service('entity.definition_update_manager')->applyUpdates();
// Clear all caches so that the base field definition, its cache in the
// entity manager, the t() cache, etc. are all cleared.
drupal_flush_all_caches();
}
/**
* Tests that translated field descriptions do not affect the update system.
*/
function testTranslatedSchemaDefinition() {
/** @var \Drupal\locale\StringDatabaseStorage $stringStorage */
$stringStorage = \Drupal::service('locale.storage');
$source = $stringStorage->createString(array(
'source' => 'Revision ID',
))->save();
$stringStorage->createTranslation(array(
'lid' => $source->lid,
'language' => 'fr',
'translation' => 'Translated Revision ID',
))->save();
// Ensure that the field is translated when access through the API.
$this->assertEqual('Translated Revision ID', \Drupal::entityManager()->getBaseFieldDefinitions('node')['vid']->getLabel());
// Assert there are no updates.
$this->assertFalse(\Drupal::service('entity.definition_update_manager')->needsUpdates());
}
/**
* Tests that translations do not affect the update system.
*/
function testTranslatedUpdate() {
// Visit the update page to collect any strings that may be translatable.
$user = $this->drupalCreateUser(array('administer software updates'));
$this->drupalLogin($user);
$update_url = $GLOBALS['base_url'] . '/update.php';
$this->drupalGet($update_url, array('external' => TRUE));
/** @var \Drupal\locale\StringDatabaseStorage $stringStorage */
$stringStorage = \Drupal::service('locale.storage');
$sources = $stringStorage->getStrings();
// Translate all source strings found.
foreach ($sources as $source) {
$stringStorage->createTranslation(array(
'lid' => $source->lid,
'language' => 'fr',
'translation' => $this->randomMachineName(100),
))->save();
}
// Ensure that there are no updates just due to translations. Check for
// markup and a link instead of specific text because text may be
// translated.
$this->drupalGet($update_url . '/selection', array('external' => TRUE));
$this->assertRaw('messages--status', 'No pending updates.');
$this->assertNoLinkByHref('fr/update.php/run', 'No link to run updates.');
}
}

View file

@ -20,16 +20,16 @@ class LocaleTranslationUiTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('locale');
public static $modules = ['locale'];
/**
* Enable interface translation to English.
*/
public function testEnglishTranslation() {
$admin_user = $this->drupalCreateUser(array('administer languages', 'access administration pages'));
$admin_user = $this->drupalCreateUser(['administer languages', 'access administration pages']);
$this->drupalLogin($admin_user);
$this->drupalPostForm('admin/config/regional/language/edit/en', array('locale_translate_english' => TRUE), t('Save language'));
$this->drupalPostForm('admin/config/regional/language/edit/en', ['locale_translate_english' => TRUE], t('Save language'));
$this->assertLinkByHref('/admin/config/regional/translate?langcode=en', 0, 'Enabled interface translation to English.');
}
@ -38,9 +38,9 @@ class LocaleTranslationUiTest extends WebTestBase {
*/
public function testStringTranslation() {
// 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']);
// User to translate and delete string.
$translate_user = $this->drupalCreateUser(array('translate interface', 'access administration pages'));
$translate_user = $this->drupalCreateUser(['translate interface', 'access administration pages']);
// Code for the language.
$langcode = 'xx';
// The English name for the language. This will be translated.
@ -51,15 +51,15 @@ class LocaleTranslationUiTest extends WebTestBase {
// Add custom language.
$this->drupalLogin($admin_user);
$edit = array(
$edit = [
'predefined_langcode' => 'custom',
'langcode' => $langcode,
'label' => $name,
'direction' => LanguageInterface::DIRECTION_LTR,
);
];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
// Add string.
t($name, array(), array('langcode' => $langcode))->render();
t($name, [], ['langcode' => $langcode])->render();
// Reset locale cache.
$this->container->get('string_translation')->reset();
$this->assertRaw('"edit-languages-' . $langcode . '-weight"', 'Language code found.');
@ -68,11 +68,11 @@ class LocaleTranslationUiTest extends WebTestBase {
// Search for the name and translate it.
$this->drupalLogin($translate_user);
$search = array(
$search = [
'string' => $name,
'langcode' => $langcode,
'translation' => 'untranslated',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$this->assertText($name, 'Search found the string as untranslated.');
@ -81,7 +81,7 @@ class LocaleTranslationUiTest extends WebTestBase {
$this->assertNoOption('edit-langcode', 'en', 'No way to translate the string to English.');
$this->drupalLogout();
$this->drupalLogin($admin_user);
$this->drupalPostForm('admin/config/regional/language/edit/en', array('locale_translate_english' => TRUE), t('Save language'));
$this->drupalPostForm('admin/config/regional/language/edit/en', ['locale_translate_english' => TRUE], t('Save language'));
$this->drupalLogout();
$this->drupalLogin($translate_user);
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
@ -90,55 +90,55 @@ class LocaleTranslationUiTest extends WebTestBase {
// Assume this is the only result, given the random name.
$textarea = current($this->xpath('//textarea'));
$lid = (string) $textarea[0]['name'];
$edit = array(
$edit = [
$lid => $translation,
);
];
$this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));
$this->assertText(t('The strings have been saved.'), 'The strings have been saved.');
$url_bits = explode('?', $this->getUrl());
$this->assertEqual($url_bits[0], \Drupal::url('locale.translate_page', array(), array('absolute' => TRUE)), 'Correct page redirection.');
$search = array(
$this->assertEqual($url_bits[0], \Drupal::url('locale.translate_page', [], ['absolute' => TRUE]), 'Correct page redirection.');
$search = [
'string' => $name,
'langcode' => $langcode,
'translation' => 'translated',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$this->assertRaw($translation, 'Non-English translation properly saved.');
$search = array(
$search = [
'string' => $name,
'langcode' => 'en',
'translation' => 'untranslated',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$textarea = current($this->xpath('//textarea'));
$lid = (string) $textarea[0]['name'];
$edit = array(
$edit = [
$lid => $translation_to_en,
);
];
$this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));
$search = array(
$search = [
'string' => $name,
'langcode' => 'en',
'translation' => 'translated',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$this->assertRaw($translation_to_en, 'English translation properly saved.');
$this->assertTrue($name != $translation && t($name, array(), array('langcode' => $langcode)) == $translation, 't() works for non-English.');
$this->assertTrue($name != $translation && t($name, [], ['langcode' => $langcode]) == $translation, 't() works for non-English.');
// Refresh the locale() cache to get fresh data from t() below. We are in
// the same HTTP request and therefore t() is not refreshed by saving the
// translation above.
$this->container->get('string_translation')->reset();
// Now we should get the proper fresh translation from t().
$this->assertTrue($name != $translation_to_en && t($name, array(), array('langcode' => 'en')) == $translation_to_en, 't() works for English.');
$this->assertTrue(t($name, array(), array('langcode' => LanguageInterface::LANGCODE_SYSTEM)) == $name, 't() works for LanguageInterface::LANGCODE_SYSTEM.');
$this->assertTrue($name != $translation_to_en && t($name, [], ['langcode' => 'en']) == $translation_to_en, 't() works for English.');
$this->assertTrue(t($name, [], ['langcode' => LanguageInterface::LANGCODE_SYSTEM]) == $name, 't() works for LanguageInterface::LANGCODE_SYSTEM.');
$search = array(
$search = [
'string' => $name,
'langcode' => 'en',
'translation' => 'untranslated',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$this->assertText(t('No strings available.'), 'String is translated.');
@ -148,17 +148,17 @@ class LocaleTranslationUiTest extends WebTestBase {
$this->assertText('Enter the password that accompanies your username.');
$this->drupalLogin($translate_user);
$search = array(
$search = [
'string' => 'accompanies your username',
'langcode' => $langcode,
'translation' => 'untranslated',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$textarea = current($this->xpath('//textarea'));
$lid = (string) $textarea[0]['name'];
$edit = array(
$edit = [
$lid => 'Please enter your Llama username.',
);
];
$this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));
$this->drupalLogout();
@ -169,9 +169,9 @@ class LocaleTranslationUiTest extends WebTestBase {
$this->drupalLogin($admin_user);
$path = 'admin/config/regional/language/delete/' . $langcode;
// This a confirm form, we do not need any fields changed.
$this->drupalPostForm($path, array(), t('Delete'));
$this->drupalPostForm($path, [], 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.');
// Reload to remove $name.
$this->drupalGet($path);
@ -181,26 +181,26 @@ class LocaleTranslationUiTest extends WebTestBase {
// Delete the string.
$this->drupalLogin($translate_user);
$search = array(
$search = [
'string' => $name,
'langcode' => 'en',
'translation' => 'translated',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
// Assume this is the only result, given the random name.
$textarea = current($this->xpath('//textarea'));
$lid = (string) $textarea[0]['name'];
$edit = array(
$edit = [
$lid => '',
);
];
$this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));
$this->assertRaw($name, 'The strings have been saved.');
$this->drupalLogin($translate_user);
$search = array(
$search = [
'string' => $name,
'langcode' => 'en',
'translation' => 'untranslated',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$this->assertNoText(t('No strings available.'), 'The translation has been removed');
}
@ -210,7 +210,7 @@ class LocaleTranslationUiTest extends WebTestBase {
* properly created and rebuilt on deletion.
*/
public function testJavaScriptTranslation() {
$user = $this->drupalCreateUser(array('translate interface', 'administer languages', 'access administration pages'));
$user = $this->drupalCreateUser(['translate interface', 'administer languages', 'access administration pages']);
$this->drupalLogin($user);
$config = $this->config('locale.settings');
@ -219,12 +219,12 @@ class LocaleTranslationUiTest extends WebTestBase {
$name = $this->randomMachineName(16);
// Add custom language.
$edit = array(
$edit = [
'predefined_langcode' => 'custom',
'langcode' => $langcode,
'label' => $name,
'direction' => LanguageInterface::DIRECTION_LTR,
);
];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
$this->container->get('language_manager')->reset();
@ -234,38 +234,38 @@ class LocaleTranslationUiTest extends WebTestBase {
// {locales_source} table and translate it.
$query = db_select('locales_source', 's');
$query->addJoin('INNER', 'locales_location', 'l', 's.lid = l.lid');
$source = $query->fields('s', array('source'))
$source = $query->fields('s', ['source'])
->condition('l.type', 'javascript')
->range(0, 1)
->execute()
->fetchField();
$search = array(
$search = [
'string' => $source,
'langcode' => $langcode,
'translation' => 'all',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$textarea = current($this->xpath('//textarea'));
$lid = (string) $textarea[0]['name'];
$edit = array(
$edit = [
$lid => $this->randomMachineName(),
);
];
$this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));
// Trigger JavaScript translation parsing and building.
_locale_rebuild_js($langcode);
$locale_javascripts = \Drupal::state()->get('locale.translation.javascript') ?: array();
$locale_javascripts = \Drupal::state()->get('locale.translation.javascript') ?: [];
$js_file = 'public://' . $config->get('javascript.directory') . '/' . $langcode . '_' . $locale_javascripts[$langcode] . '.js';
$this->assertTrue($result = file_exists($js_file), SafeMarkup::format('JavaScript file created: %file', array('%file' => $result ? $js_file : 'not found')));
$this->assertTrue($result = file_exists($js_file), SafeMarkup::format('JavaScript file created: %file', ['%file' => $result ? $js_file : 'not found']));
// Test JavaScript translation rebuilding.
file_unmanaged_delete($js_file);
$this->assertTrue($result = !file_exists($js_file), SafeMarkup::format('JavaScript file deleted: %file', array('%file' => $result ? $js_file : 'found')));
$this->assertTrue($result = !file_exists($js_file), SafeMarkup::format('JavaScript file deleted: %file', ['%file' => $result ? $js_file : 'found']));
_locale_rebuild_js($langcode);
$this->assertTrue($result = file_exists($js_file), SafeMarkup::format('JavaScript file rebuilt: %file', array('%file' => $result ? $js_file : 'not found')));
$this->assertTrue($result = file_exists($js_file), SafeMarkup::format('JavaScript file rebuilt: %file', ['%file' => $result ? $js_file : 'not found']));
}
/**
@ -273,7 +273,7 @@ class LocaleTranslationUiTest extends WebTestBase {
*/
public function testStringValidation() {
// User to add language and strings.
$admin_user = $this->drupalCreateUser(array('administer languages', 'access administration pages', 'translate interface'));
$admin_user = $this->drupalCreateUser(['administer languages', 'access administration pages', 'translate interface']);
$this->drupalLogin($admin_user);
$langcode = 'xx';
// The English name for the language. This will be translated.
@ -290,30 +290,30 @@ class LocaleTranslationUiTest extends WebTestBase {
$bad_translations[$key] = "<BODY ONLOAD=alert('xss')>" . $key;
// Add custom language.
$edit = array(
$edit = [
'predefined_langcode' => 'custom',
'langcode' => $langcode,
'label' => $name,
'direction' => LanguageInterface::DIRECTION_LTR,
);
];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
// Add string.
t($name, array(), array('langcode' => $langcode))->render();
t($name, [], ['langcode' => $langcode])->render();
// Reset locale cache.
$search = array(
$search = [
'string' => $name,
'langcode' => $langcode,
'translation' => 'all',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
// Find the edit path.
$textarea = current($this->xpath('//textarea'));
$lid = (string) $textarea[0]['name'];
foreach ($bad_translations as $translation) {
$edit = array(
$edit = [
$lid => $translation,
);
];
$this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));
// Check for a form error on the textarea.
$form_class = $this->xpath('//form[@id="locale-translate-edit-form"]//textarea/@class');
@ -327,9 +327,9 @@ class LocaleTranslationUiTest extends WebTestBase {
*/
public function testStringSearch() {
// 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']);
// User to translate and delete string.
$translate_user = $this->drupalCreateUser(array('translate interface', 'access administration pages'));
$translate_user = $this->drupalCreateUser(['translate interface', 'access administration pages']);
// Code for the language.
$langcode = 'xx';
@ -340,35 +340,35 @@ class LocaleTranslationUiTest extends WebTestBase {
// Add custom language.
$this->drupalLogin($admin_user);
$edit = array(
$edit = [
'predefined_langcode' => 'custom',
'langcode' => $langcode,
'label' => $name,
'direction' => LanguageInterface::DIRECTION_LTR,
);
];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
$edit = array(
$edit = [
'predefined_langcode' => 'custom',
'langcode' => 'yy',
'label' => $this->randomMachineName(16),
'direction' => LanguageInterface::DIRECTION_LTR,
);
];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
// Add string.
t($name, array(), array('langcode' => $langcode))->render();
t($name, [], ['langcode' => $langcode])->render();
// Reset locale cache.
$this->container->get('string_translation')->reset();
$this->drupalLogout();
// Search for the name.
$this->drupalLogin($translate_user);
$search = array(
$search = [
'string' => $name,
'langcode' => $langcode,
'translation' => 'all',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
// assertText() seems to remove the input field where $name always could be
// found, so this is not a false assert. See how assertNoText succeeds
@ -377,21 +377,21 @@ class LocaleTranslationUiTest extends WebTestBase {
// Ensure untranslated string doesn't appear if searching on 'only
// translated strings'.
$search = array(
$search = [
'string' => $name,
'langcode' => $langcode,
'translation' => 'translated',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$this->assertText(t('No strings available.'), "Search didn't find the string.");
// Ensure untranslated string appears if searching on 'only untranslated
// strings'.
$search = array(
$search = [
'string' => $name,
'langcode' => $langcode,
'translation' => 'untranslated',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$this->assertNoText(t('No strings available.'), 'Search found the string.');
@ -400,66 +400,66 @@ class LocaleTranslationUiTest extends WebTestBase {
// We save the lid from the path.
$textarea = current($this->xpath('//textarea'));
$lid = (string) $textarea[0]['name'];
$edit = array(
$edit = [
$lid => $translation,
);
];
$this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));
// Ensure translated string does appear if searching on 'only
// translated strings'.
$search = array(
$search = [
'string' => $translation,
'langcode' => $langcode,
'translation' => 'translated',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$this->assertNoText(t('No strings available.'), 'Search found the translation.');
// Ensure translated source string doesn't appear if searching on 'only
// untranslated strings'.
$search = array(
$search = [
'string' => $name,
'langcode' => $langcode,
'translation' => 'untranslated',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$this->assertText(t('No strings available.'), "Search didn't find the source string.");
// Ensure translated string doesn't appear if searching on 'only
// untranslated strings'.
$search = array(
$search = [
'string' => $translation,
'langcode' => $langcode,
'translation' => 'untranslated',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$this->assertText(t('No strings available.'), "Search didn't find the translation.");
// Ensure translated string does appear if searching on the custom language.
$search = array(
$search = [
'string' => $translation,
'langcode' => $langcode,
'translation' => 'all',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$this->assertNoText(t('No strings available.'), 'Search found the translation.');
// Ensure translated string doesn't appear if searching in System (English).
$search = array(
$search = [
'string' => $translation,
'langcode' => 'yy',
'translation' => 'all',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$this->assertText(t('No strings available.'), "Search didn't find the translation.");
// Search for a string that isn't in the system.
$unavailable_string = $this->randomMachineName(16);
$search = array(
$search = [
'string' => $unavailable_string,
'langcode' => $langcode,
'translation' => 'all',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$this->assertText(t('No strings available.'), "Search didn't find the invalid string.");
}
@ -468,35 +468,35 @@ class LocaleTranslationUiTest extends WebTestBase {
* Tests that only changed strings are saved customized when edited.
*/
public function testUICustomizedStrings() {
$user = $this->drupalCreateUser(array('translate interface', 'administer languages', 'access administration pages'));
$user = $this->drupalCreateUser(['translate interface', 'administer languages', 'access administration pages']);
$this->drupalLogin($user);
ConfigurableLanguage::createFromLangcode('de')->save();
// Create test source string.
$string = $this->container->get('locale.storage')->createString(array(
$string = $this->container->get('locale.storage')->createString([
'source' => $this->randomMachineName(100),
'context' => $this->randomMachineName(20),
))->save();
])->save();
// Create translation for new string and save it as non-customized.
$translation = $this->container->get('locale.storage')->createTranslation(array(
$translation = $this->container->get('locale.storage')->createTranslation([
'lid' => $string->lid,
'language' => 'de',
'translation' => $this->randomMachineName(100),
'customized' => 0,
))->save();
])->save();
// Reset locale cache.
$this->container->get('string_translation')->reset();
// Ensure non-customized translation string does appear if searching
// non-customized translation.
$search = array(
$search = [
'string' => $string->getString(),
'langcode' => 'de',
'translation' => 'translated',
'customized' => '0',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$this->assertText($translation->getString(), 'Translation is found in search result.');
@ -504,38 +504,38 @@ class LocaleTranslationUiTest extends WebTestBase {
// Submit the translations without changing the translation.
$textarea = current($this->xpath('//textarea'));
$lid = (string) $textarea[0]['name'];
$edit = array(
$edit = [
$lid => $translation->getString(),
);
];
$this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));
// Ensure unchanged translation string does appear if searching
// non-customized translation.
$search = array(
$search = [
'string' => $string->getString(),
'langcode' => 'de',
'translation' => 'translated',
'customized' => '0',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$this->assertText($string->getString(), 'Translation is not marked as customized.');
// Submit the translations with a new translation.
$textarea = current($this->xpath('//textarea'));
$lid = (string) $textarea[0]['name'];
$edit = array(
$edit = [
$lid => $this->randomMachineName(100),
);
];
$this->drupalPostForm('admin/config/regional/translate', $edit, t('Save translations'));
// Ensure changed translation string does appear if searching customized
// translation.
$search = array(
$search = [
'string' => $string->getString(),
'langcode' => 'de',
'translation' => 'translated',
'customized' => '1',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$this->assertText($string->getString(), "Translation is marked as customized.");
}

View file

@ -45,7 +45,7 @@ abstract class LocaleUpdateBase extends WebTestBase {
*
* @var array
*/
public static $modules = array('locale', 'locale_test');
public static $modules = ['locale', 'locale_test'];
/**
* {@inheritdoc}
@ -85,10 +85,10 @@ abstract class LocaleUpdateBase extends WebTestBase {
* The language code of the language to add.
*/
protected function addLanguage($langcode) {
$edit = array('predefined_langcode' => $langcode);
$edit = ['predefined_langcode' => $langcode];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));
$this->container->get('language_manager')->reset();
$this->assertTrue(\Drupal::languageManager()->getLanguage($langcode), SafeMarkup::format('Language %langcode added.', array('%langcode' => $langcode)));
$this->assertTrue(\Drupal::languageManager()->getLanguage($langcode), SafeMarkup::format('Language %langcode added.', ['%langcode' => $langcode]));
}
/**
@ -105,7 +105,7 @@ abstract class LocaleUpdateBase extends WebTestBase {
* singular strings are supported, no plurals. No double quotes are allowed
* in source and translations strings.
*/
protected function makePoFile($path, $filename, $timestamp = NULL, array $translations = array()) {
protected function makePoFile($path, $filename, $timestamp = NULL, array $translations = []) {
$timestamp = $timestamp ? $timestamp : REQUEST_TIME;
$path = 'public://' . $path;
$text = '';
@ -184,9 +184,9 @@ EOF;
$config->set('translation.default_filename', '%project-%version.%language._po')->save();
// Setting up sets of translations for the translation files.
$translations_one = array('January' => 'Januar_1', 'February' => 'Februar_1', 'March' => 'Marz_1');
$translations_two = array('February' => 'Februar_2', 'March' => 'Marz_2', 'April' => 'April_2');
$translations_three = array('April' => 'April_3', 'May' => 'Mai_3', 'June' => 'Juni_3');
$translations_one = ['January' => 'Januar_1', 'February' => 'Februar_1', 'March' => 'Marz_1'];
$translations_two = ['February' => 'Februar_2', 'March' => 'Marz_2', 'April' => 'April_2'];
$translations_three = ['April' => 'April_3', 'May' => 'Mai_3', 'June' => 'Juni_3'];
// Add a number of files to the local file system to serve as remote
// translation server and match the project definitions set in
@ -212,71 +212,71 @@ EOF;
// Add non customized translations to the database.
$langcode = 'de';
$context = '';
$non_customized_translations = array(
$non_customized_translations = [
'March' => 'Marz',
'June' => 'Juni',
);
];
foreach ($non_customized_translations as $source => $translation) {
$string = $this->container->get('locale.storage')->createString(array(
$string = $this->container->get('locale.storage')->createString([
'source' => $source,
'context' => $context,
))
])
->save();
$this->container->get('locale.storage')->createTranslation(array(
$this->container->get('locale.storage')->createTranslation([
'lid' => $string->getId(),
'language' => $langcode,
'translation' => $translation,
'customized' => LOCALE_NOT_CUSTOMIZED,
))->save();
])->save();
}
// Add customized translations to the database.
$customized_translations = array(
$customized_translations = [
'January' => 'Januar_customized',
'February' => 'Februar_customized',
'May' => 'Mai_customized',
);
];
foreach ($customized_translations as $source => $translation) {
$string = $this->container->get('locale.storage')->createString(array(
$string = $this->container->get('locale.storage')->createString([
'source' => $source,
'context' => $context,
))
])
->save();
$this->container->get('locale.storage')->createTranslation(array(
$this->container->get('locale.storage')->createTranslation([
'lid' => $string->getId(),
'language' => $langcode,
'translation' => $translation,
'customized' => LOCALE_CUSTOMIZED,
))->save();
])->save();
}
// Add a state of current translations in locale_files.
$default = array(
$default = [
'langcode' => $langcode,
'uri' => '',
'timestamp' => $this->timestampMedium,
'last_checked' => $this->timestampMedium,
);
$data[] = array(
];
$data[] = [
'project' => 'contrib_module_one',
'filename' => 'contrib_module_one-8.x-1.1.de._po',
'version' => '8.x-1.1',
);
$data[] = array(
];
$data[] = [
'project' => 'contrib_module_two',
'filename' => 'contrib_module_two-8.x-2.0-beta4.de._po',
'version' => '8.x-2.0-beta4',
);
$data[] = array(
];
$data[] = [
'project' => 'contrib_module_three',
'filename' => 'contrib_module_three-8.x-1.0.de._po',
'version' => '8.x-1.0',
);
$data[] = array(
];
$data[] = [
'project' => 'custom_module_one',
'filename' => 'custom_module_one.de.po',
'version' => '',
);
];
foreach ($data as $file) {
$file = array_merge($default, $file);
db_insert('locale_file')->fields($file)->execute();
@ -297,9 +297,9 @@ EOF;
* (optional) A message to display with the assertion.
*/
protected function assertTranslation($source, $translation, $langcode, $message = '') {
$db_translation = db_query('SELECT translation FROM {locales_target} lt INNER JOIN {locales_source} ls ON ls.lid = lt.lid WHERE ls.source = :source AND lt.language = :langcode', array(':source' => $source, ':langcode' => $langcode))->fetchField();
$db_translation = db_query('SELECT translation FROM {locales_target} lt INNER JOIN {locales_source} ls ON ls.lid = lt.lid WHERE ls.source = :source AND lt.language = :langcode', [':source' => $source, ':langcode' => $langcode])->fetchField();
$db_translation = $db_translation == FALSE ? '' : $db_translation;
$this->assertEqual($translation, $db_translation, $message ? $message : format_string('Correct translation of %source (%language)', array('%source' => $source, '%language' => $langcode)));
$this->assertEqual($translation, $db_translation, $message ? $message : format_string('Correct translation of %source (%language)', ['%source' => $source, '%language' => $langcode]));
}
}

View file

@ -9,14 +9,14 @@ namespace Drupal\locale\Tests;
*/
class LocaleUpdateCronTest extends LocaleUpdateBase {
protected $batchOutput = array();
protected $batchOutput = [];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$admin_user = $this->drupalCreateUser(array('administer modules', 'administer site configuration', 'administer languages', 'access administration pages', 'translate interface'));
$admin_user = $this->drupalCreateUser(['administer modules', 'administer site configuration', 'administer languages', 'access administration pages', 'translate interface']);
$this->drupalLogin($admin_user);
$this->addLanguage('de');
}
@ -35,7 +35,7 @@ class LocaleUpdateCronTest extends LocaleUpdateBase {
// Update translations using batch to ensure a clean test starting point.
$this->drupalGet('admin/reports/translations/check');
$this->drupalPostForm('admin/reports/translations', array(), t('Update translations'));
$this->drupalPostForm('admin/reports/translations', [], t('Update translations'));
// Store translation status for comparison.
$initial_history = locale_translation_get_file_history();
@ -48,16 +48,16 @@ class LocaleUpdateCronTest extends LocaleUpdateBase {
// Prepare for test: Simulate that the file has not been checked for a long
// time. Set the last_check timestamp to zero.
$query = db_update('locale_file');
$query->fields(array('last_checked' => 0));
$query->fields(['last_checked' => 0]);
$query->condition('project', 'contrib_module_two');
$query->condition('langcode', 'de');
$query->execute();
// Test: Disable cron update and verify that no tasks are added to the
// queue.
$edit = array(
$edit = [
'update_interval_days' => 0,
);
];
$this->drupalPostForm('admin/config/regional/translate/settings', $edit, t('Save configuration'));
// Execute locale cron tasks to add tasks to the queue.
@ -70,9 +70,9 @@ class LocaleUpdateCronTest extends LocaleUpdateBase {
// Test: Enable cron update and check if update tasks are added to the
// queue.
// Set cron update to Weekly.
$edit = array(
$edit = [
'update_interval_days' => 7,
);
];
$this->drupalPostForm('admin/config/regional/translate/settings', $edit, t('Save configuration'));
// Execute locale cron tasks to add tasks to the queue.

View file

@ -11,14 +11,14 @@ use Drupal\simpletest\WebTestBase;
*/
class LocaleUpdateDevelopmentReleaseTest extends WebTestBase {
public static $modules = array('locale', 'locale_test_development_release');
public static $modules = ['locale', 'locale_test_development_release'];
protected function setUp() {
parent::setUp();
module_load_include('compare.inc', 'locale');
$admin_user = $this->drupalCreateUser(array('administer modules', 'administer languages', 'access administration pages', 'translate interface'));
$admin_user = $this->drupalCreateUser(['administer modules', 'administer languages', 'access administration pages', 'translate interface']);
$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'));
}
public function testLocaleUpdateDevelopmentRelease() {

View file

@ -17,14 +17,14 @@ class LocaleUpdateInterfaceTest extends LocaleUpdateBase {
*
* @var array
*/
public static $modules = array('locale_test_translate');
public static $modules = ['locale_test_translate'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$admin_user = $this->drupalCreateUser(array('administer modules', 'administer site configuration', 'administer languages', 'access administration pages', 'translate interface'));
$admin_user = $this->drupalCreateUser(['administer modules', 'administer site configuration', 'administer languages', 'access administration pages', 'translate interface']);
$this->drupalLogin($admin_user);
}
@ -41,7 +41,7 @@ class LocaleUpdateInterfaceTest extends LocaleUpdateBase {
$this->assertNoText(t('Translation update status'), 'No status message');
$this->drupalGet('admin/reports/translations');
$this->assertRaw(t('No translatable languages available. <a href=":add_language">Add a language</a> first.', array(':add_language' => \Drupal::url('entity.configurable_language.collection'))), 'Language message');
$this->assertRaw(t('No translatable languages available. <a href=":add_language">Add a language</a> first.', [':add_language' => \Drupal::url('entity.configurable_language.collection')]), 'Language message');
// Add German language.
$this->addLanguage('de');
@ -49,7 +49,7 @@ class LocaleUpdateInterfaceTest extends LocaleUpdateBase {
// Override Drupal core translation status as 'up-to-date'.
$status = locale_translation_get_status();
$status['drupal']['de']->type = 'current';
\Drupal::state()->set('locale.translation_status', $status);
\Drupal::keyValue('locale.translation_status')->set('drupal', $status['drupal']);
// One language added, all translations up to date.
$this->drupalGet('admin/reports/status');
@ -61,32 +61,32 @@ class LocaleUpdateInterfaceTest extends LocaleUpdateBase {
// Set locale_test_translate module to have a local translation available.
$status = locale_translation_get_status();
$status['locale_test_translate']['de']->type = 'local';
\Drupal::state()->set('locale.translation_status', $status);
\Drupal::keyValue('locale.translation_status')->set('locale_test_translate', $status['locale_test_translate']);
// Check if updates are available for German.
$this->drupalGet('admin/reports/status');
$this->assertText(t('Translation update status'), 'Status message');
$this->assertRaw(t('Updates available for: @languages. See the <a href=":updates">Available translation updates</a> page for more information.', array('@languages' => t('German'), ':updates' => \Drupal::url('locale.translate_status'))), 'Updates available message');
$this->assertRaw(t('Updates available for: @languages. See the <a href=":updates">Available translation updates</a> page for more information.', ['@languages' => t('German'), ':updates' => \Drupal::url('locale.translate_status')]), 'Updates available message');
$this->drupalGet('admin/reports/translations');
$this->assertText(t('Updates for: @modules', array('@modules' => 'Locale test translate')), 'Translations available');
$this->assertText(t('Updates for: @modules', ['@modules' => 'Locale test translate']), 'Translations available');
// Set locale_test_translate module to have a dev release and no
// translation found.
$status = locale_translation_get_status();
$status['locale_test_translate']['de']->version = '1.3-dev';
$status['locale_test_translate']['de']->type = '';
\Drupal::state()->set('locale.translation_status', $status);
\Drupal::keyValue('locale.translation_status')->set('locale_test_translate', $status['locale_test_translate']);
// Check if no updates were found.
$this->drupalGet('admin/reports/status');
$this->assertText(t('Translation update status'), 'Status message');
$this->assertRaw(t('Missing translations for: @languages. See the <a href=":updates">Available translation updates</a> page for more information.', array('@languages' => t('German'), ':updates' => \Drupal::url('locale.translate_status'))), 'Missing translations message');
$this->assertRaw(t('Missing translations for: @languages. See the <a href=":updates">Available translation updates</a> page for more information.', ['@languages' => t('German'), ':updates' => \Drupal::url('locale.translate_status')]), 'Missing translations message');
$this->drupalGet('admin/reports/translations');
$this->assertText(t('Missing translations for one project'), 'No translations found');
$release_details = new FormattableMarkup('@module (@version). @info', [
'@module' => 'Locale test translate',
'@version' => '1.3-dev',
'@info' => t('File not found at %local_path', array('%local_path' => 'core/modules/locale/tests/test.de.po'))
'@info' => t('File not found at %local_path', ['%local_path' => 'core/modules/locale/tests/test.de.po'])
]);
$this->assertRaw($release_details->__toString(), 'Release details');
@ -95,24 +95,24 @@ class LocaleUpdateInterfaceTest extends LocaleUpdateBase {
$status['drupal']['de']->type = '';
$status['drupal']['de']->timestamp = 0;
$status['drupal']['de']->version = '8.1.1';
\Drupal::state()->set('locale.translation_status', $status);
\Drupal::keyValue('locale.translation_status')->set('drupal', $status['drupal']);
// Check if Drupal core is not translated.
$this->drupalGet('admin/reports/translations');
$this->assertText(t('Missing translations for 2 projects'), 'No translations found');
$this->assertText(t('@module (@version).', array('@module' => t('Drupal core'), '@version' => '8.1.1')), 'Release details');
$this->assertText(t('@module (@version).', ['@module' => t('Drupal core'), '@version' => '8.1.1']), 'Release details');
// Override Drupal core translation status as 'translations available'.
$status = locale_translation_get_status();
$status['drupal']['de']->type = 'local';
$status['drupal']['de']->files['local']->timestamp = REQUEST_TIME;
$status['drupal']['de']->files['local']->info['version'] = '8.1.1';
\Drupal::state()->set('locale.translation_status', $status);
\Drupal::keyValue('locale.translation_status')->set('drupal', $status['drupal']);
// Check if translations are available for Drupal core.
$this->drupalGet('admin/reports/translations');
$this->assertText(t('Updates for: @project', array('@project' => t('Drupal core'))), 'Translations found');
$this->assertText(SafeMarkup::format('@module (@date)', array('@module' => t('Drupal core'), '@date' => format_date(REQUEST_TIME, 'html_date'))), 'Core translation update');
$this->assertText(t('Updates for: @project', ['@project' => t('Drupal core')]), 'Translations found');
$this->assertText(SafeMarkup::format('@module (@date)', ['@module' => t('Drupal core'), '@date' => format_date(REQUEST_TIME, 'html_date')]), 'Core translation update');
$update_button = $this->xpath('//input[@type="submit"][@value="' . t('Update translations') . '"]');
$this->assertTrue($update_button, 'Update translations button');
}

View file

@ -18,7 +18,7 @@ class LocaleUpdateTest extends LocaleUpdateBase {
parent::setUp();
module_load_include('compare.inc', 'locale');
module_load_include('fetch.inc', 'locale');
$admin_user = $this->drupalCreateUser(array('administer modules', 'administer site configuration', 'administer languages', 'access administration pages', 'translate interface'));
$admin_user = $this->drupalCreateUser(['administer modules', 'administer site configuration', 'administer languages', 'access administration pages', 'translate interface']);
$this->drupalLogin($admin_user);
// We use German as test language. This language must match the translation
// file that come with the locale_test module (test.de.po) and can therefore
@ -42,7 +42,7 @@ class LocaleUpdateTest extends LocaleUpdateBase {
$projects = locale_translation_project_list();
$this->assertFalse(isset($projects['locale_test_translate']), 'Hidden module not found');
$this->assertEqual($projects['locale_test']['info']['interface translation server pattern'], 'core/modules/locale/test/test.%language.po', 'Interface translation parameter found in project info.');
$this->assertEqual($projects['locale_test']['name'], 'locale_test', format_string('%key found in project info.', array('%key' => 'interface translation project')));
$this->assertEqual($projects['locale_test']['name'], 'locale_test', format_string('%key found in project info.', ['%key' => 'interface translation project']));
}
/**
@ -74,9 +74,9 @@ class LocaleUpdateTest extends LocaleUpdateBase {
$config->set('translation.default_filename', '%project-%version.%language._po')->save();
// Set the test conditions.
$edit = array(
$edit = [
'use_source' => LOCALE_TRANSLATION_USE_SOURCE_LOCAL,
);
];
$this->drupalPostForm('admin/config/regional/translate/settings', $edit, t('Save configuration'));
// Get status of translation sources at local file system.
@ -90,9 +90,9 @@ class LocaleUpdateTest extends LocaleUpdateBase {
$this->assertEqual($result['custom_module_one']['de']->type, LOCALE_TRANSLATION_LOCAL, 'Translation of custom_module_one found');
// Set the test conditions.
$edit = array(
$edit = [
'use_source' => LOCALE_TRANSLATION_USE_SOURCE_REMOTE_AND_LOCAL,
);
];
$this->drupalPostForm('admin/config/regional/translate/settings', $edit, t('Save configuration'));
// Get status of translation sources at both local and remote locations.
@ -124,10 +124,10 @@ class LocaleUpdateTest extends LocaleUpdateBase {
$config->set('translation.default_filename', '%project-%version.%language._po');
// Set the update conditions for this test.
$edit = array(
$edit = [
'use_source' => LOCALE_TRANSLATION_USE_SOURCE_REMOTE_AND_LOCAL,
'overwrite' => LOCALE_TRANSLATION_OVERWRITE_ALL,
);
];
$this->drupalPostForm('admin/config/regional/translate/settings', $edit, t('Save configuration'));
// Get the translation status.
@ -140,7 +140,7 @@ class LocaleUpdateTest extends LocaleUpdateBase {
$this->assertText('Contributed module two (' . format_date($this->timestampNew, 'html_date') . ')', 'Updates for Contrib module two');
// Execute the translation update.
$this->drupalPostForm('admin/reports/translations', array(), t('Update translations'));
$this->drupalPostForm('admin/reports/translations', [], t('Update translations'));
// Check if the translation has been updated, using the status cache.
$status = locale_translation_get_status();
@ -161,13 +161,13 @@ class LocaleUpdateTest extends LocaleUpdateBase {
$this->assertEqual($history['contrib_module_three']['de']->last_checked, $this->timestampMedium, 'Translation of contrib_module_three is not updated');
// Check whether existing translations have (not) been overwritten.
$this->assertEqual(t('January', array(), array('langcode' => 'de')), 'Januar_1', 'Translation of January');
$this->assertEqual(t('February', array(), array('langcode' => 'de')), 'Februar_2', 'Translation of February');
$this->assertEqual(t('March', array(), array('langcode' => 'de')), 'Marz_2', 'Translation of March');
$this->assertEqual(t('April', array(), array('langcode' => 'de')), 'April_2', 'Translation of April');
$this->assertEqual(t('May', array(), array('langcode' => 'de')), 'Mai_customized', 'Translation of May');
$this->assertEqual(t('June', array(), array('langcode' => 'de')), 'Juni', 'Translation of June');
$this->assertEqual(t('Monday', array(), array('langcode' => 'de')), 'Montag', 'Translation of Monday');
$this->assertEqual(t('January', [], ['langcode' => 'de']), 'Januar_1', 'Translation of January');
$this->assertEqual(t('February', [], ['langcode' => 'de']), 'Februar_2', 'Translation of February');
$this->assertEqual(t('March', [], ['langcode' => 'de']), 'Marz_2', 'Translation of March');
$this->assertEqual(t('April', [], ['langcode' => 'de']), 'April_2', 'Translation of April');
$this->assertEqual(t('May', [], ['langcode' => 'de']), 'Mai_customized', 'Translation of May');
$this->assertEqual(t('June', [], ['langcode' => 'de']), 'Juni', 'Translation of June');
$this->assertEqual(t('Monday', [], ['langcode' => 'de']), 'Montag', 'Translation of Monday');
}
/**
@ -186,15 +186,15 @@ class LocaleUpdateTest extends LocaleUpdateBase {
$config->set('translation.default_filename', '%project-%version.%language._po');
// Set the update conditions for this test.
$edit = array(
$edit = [
'use_source' => LOCALE_TRANSLATION_USE_SOURCE_LOCAL,
'overwrite' => LOCALE_TRANSLATION_OVERWRITE_ALL,
);
];
$this->drupalPostForm('admin/config/regional/translate/settings', $edit, t('Save configuration'));
// Execute the translation update.
$this->drupalGet('admin/reports/translations/check');
$this->drupalPostForm('admin/reports/translations', array(), t('Update translations'));
$this->drupalPostForm('admin/reports/translations', [], t('Update translations'));
// Check if the translation has been updated, using the status cache.
$status = locale_translation_get_status();
@ -215,13 +215,13 @@ class LocaleUpdateTest extends LocaleUpdateBase {
$this->assertEqual($history['contrib_module_three']['de']->last_checked, $this->timestampMedium, 'Translation of contrib_module_three is not updated');
// Check whether existing translations have (not) been overwritten.
$this->assertEqual(t('January', array(), array('langcode' => 'de')), 'Januar_customized', 'Translation of January');
$this->assertEqual(t('February', array(), array('langcode' => 'de')), 'Februar_2', 'Translation of February');
$this->assertEqual(t('March', array(), array('langcode' => 'de')), 'Marz_2', 'Translation of March');
$this->assertEqual(t('April', array(), array('langcode' => 'de')), 'April_2', 'Translation of April');
$this->assertEqual(t('May', array(), array('langcode' => 'de')), 'Mai_customized', 'Translation of May');
$this->assertEqual(t('June', array(), array('langcode' => 'de')), 'Juni', 'Translation of June');
$this->assertEqual(t('Monday', array(), array('langcode' => 'de')), 'Montag', 'Translation of Monday');
$this->assertEqual(t('January', [], ['langcode' => 'de']), 'Januar_customized', 'Translation of January');
$this->assertEqual(t('February', [], ['langcode' => 'de']), 'Februar_2', 'Translation of February');
$this->assertEqual(t('March', [], ['langcode' => 'de']), 'Marz_2', 'Translation of March');
$this->assertEqual(t('April', [], ['langcode' => 'de']), 'April_2', 'Translation of April');
$this->assertEqual(t('May', [], ['langcode' => 'de']), 'Mai_customized', 'Translation of May');
$this->assertEqual(t('June', [], ['langcode' => 'de']), 'Juni', 'Translation of June');
$this->assertEqual(t('Monday', [], ['langcode' => 'de']), 'Montag', 'Translation of Monday');
}
/**
@ -240,24 +240,24 @@ class LocaleUpdateTest extends LocaleUpdateBase {
$config->set('translation.default_filename', '%project-%version.%language._po');
// Set the test conditions.
$edit = array(
$edit = [
'use_source' => LOCALE_TRANSLATION_USE_SOURCE_REMOTE_AND_LOCAL,
'overwrite' => LOCALE_TRANSLATION_OVERWRITE_NON_CUSTOMIZED,
);
];
$this->drupalPostForm('admin/config/regional/translate/settings', $edit, t('Save configuration'));
// Execute translation update.
$this->drupalGet('admin/reports/translations/check');
$this->drupalPostForm('admin/reports/translations', array(), t('Update translations'));
$this->drupalPostForm('admin/reports/translations', [], t('Update translations'));
// Check whether existing translations have (not) been overwritten.
$this->assertEqual(t('January', array(), array('langcode' => 'de')), 'Januar_customized', 'Translation of January');
$this->assertEqual(t('February', array(), array('langcode' => 'de')), 'Februar_customized', 'Translation of February');
$this->assertEqual(t('March', array(), array('langcode' => 'de')), 'Marz_2', 'Translation of March');
$this->assertEqual(t('April', array(), array('langcode' => 'de')), 'April_2', 'Translation of April');
$this->assertEqual(t('May', array(), array('langcode' => 'de')), 'Mai_customized', 'Translation of May');
$this->assertEqual(t('June', array(), array('langcode' => 'de')), 'Juni', 'Translation of June');
$this->assertEqual(t('Monday', array(), array('langcode' => 'de')), 'Montag', 'Translation of Monday');
$this->assertEqual(t('January', [], ['langcode' => 'de']), 'Januar_customized', 'Translation of January');
$this->assertEqual(t('February', [], ['langcode' => 'de']), 'Februar_customized', 'Translation of February');
$this->assertEqual(t('March', [], ['langcode' => 'de']), 'Marz_2', 'Translation of March');
$this->assertEqual(t('April', [], ['langcode' => 'de']), 'April_2', 'Translation of April');
$this->assertEqual(t('May', [], ['langcode' => 'de']), 'Mai_customized', 'Translation of May');
$this->assertEqual(t('June', [], ['langcode' => 'de']), 'Juni', 'Translation of June');
$this->assertEqual(t('Monday', [], ['langcode' => 'de']), 'Montag', 'Translation of Monday');
}
/**
@ -276,15 +276,15 @@ class LocaleUpdateTest extends LocaleUpdateBase {
$config->set('translation.default_filename', '%project-%version.%language._po');
// Set the test conditions.
$edit = array(
$edit = [
'use_source' => LOCALE_TRANSLATION_USE_SOURCE_REMOTE_AND_LOCAL,
'overwrite' => LOCALE_TRANSLATION_OVERWRITE_NONE,
);
];
$this->drupalPostForm('admin/config/regional/translate/settings', $edit, t('Save configuration'));
// Execute translation update.
$this->drupalGet('admin/reports/translations/check');
$this->drupalPostForm('admin/reports/translations', array(), t('Update translations'));
$this->drupalPostForm('admin/reports/translations', [], t('Update translations'));
// Check whether existing translations have (not) been overwritten.
$this->assertTranslation('January', 'Januar_customized', 'de');
@ -307,21 +307,21 @@ class LocaleUpdateTest extends LocaleUpdateBase {
$this->assertTranslation('Tuesday', '', 'de');
// Enable a module.
$edit = array(
'modules[Testing][locale_test_translate][enable]' => 'locale_test_translate',
);
$edit = [
'modules[locale_test_translate][enable]' => 'locale_test_translate',
];
$this->drupalPostForm('admin/modules', $edit, t('Install'));
// Check if translations have been imported.
$this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.',
array('%number' => 7, '%update' => 0, '%delete' => 0)), 'One translation file imported.');
['%number' => 7, '%update' => 0, '%delete' => 0]), 'One translation file imported.');
$this->assertTranslation('Tuesday', 'Dienstag', 'de');
$edit = array(
$edit = [
'uninstall[locale_test_translate]' => 1,
);
];
$this->drupalPostForm('admin/modules/uninstall', $edit, t('Uninstall'));
$this->drupalPostForm(NULL, array(), t('Uninstall'));
$this->drupalPostForm(NULL, [], t('Uninstall'));
// Check if the file data is removed from the database.
$history = locale_translation_get_file_history();
@ -342,9 +342,9 @@ class LocaleUpdateTest extends LocaleUpdateBase {
\Drupal::state()->set('locale.test_system_info_alter', TRUE);
// Enable a module.
$edit = array(
'modules[Testing][locale_test_translate][enable]' => 'locale_test_translate',
);
$edit = [
'modules[locale_test_translate][enable]' => 'locale_test_translate',
];
$this->drupalPostForm('admin/modules', $edit, t('Install'));
// Check if there is no Dutch translation yet.
@ -352,14 +352,14 @@ class LocaleUpdateTest extends LocaleUpdateBase {
$this->assertTranslation('Tuesday', 'Dienstag', 'de');
// Add a language.
$edit = array(
$edit = [
'predefined_langcode' => 'nl',
);
];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));
// Check if the right number of translations are added.
$this->assertRaw(t('One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.',
array('%number' => 8, '%update' => 0, '%delete' => 0)), 'One language added.');
['%number' => 8, '%update' => 0, '%delete' => 0]), 'One language added.');
$this->assertTranslation('Extraday', 'extra dag', 'nl');
// Check if the language data is added to the database.
@ -367,7 +367,7 @@ class LocaleUpdateTest extends LocaleUpdateBase {
$this->assertTrue($result, 'Files added to file history');
// Remove a language.
$this->drupalPostForm('admin/config/regional/language/delete/nl', array(), t('Delete'));
$this->drupalPostForm('admin/config/regional/language/delete/nl', [], t('Delete'));
// Check if the language data is removed from the database.
$result = db_query("SELECT project FROM {locale_file} WHERE langcode='nl'")->fetchField();
@ -386,21 +386,21 @@ class LocaleUpdateTest extends LocaleUpdateBase {
\Drupal::state()->set('locale.test_system_info_alter', TRUE);
// Enable a module.
$edit = array(
'modules[Testing][locale_test_translate][enable]' => 'locale_test_translate',
);
$edit = [
'modules[locale_test_translate][enable]' => 'locale_test_translate',
];
$this->drupalPostForm('admin/modules', $edit, t('Install'));
// Create a custom language with language code 'xx' and a random
// name.
$langcode = 'xx';
$name = $this->randomMachineName(16);
$edit = array(
$edit = [
'predefined_langcode' => 'custom',
'langcode' => $langcode,
'label' => $name,
'direction' => LanguageInterface::DIRECTION_LTR,
);
];
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add custom language'));
// Ensure the translation file is automatically imported when the language
@ -409,31 +409,31 @@ class LocaleUpdateTest extends LocaleUpdateBase {
$this->assertText(t('One translation string was skipped because of disallowed or malformed HTML'), 'Language file automatically imported.');
// Ensure the strings were successfully imported.
$search = array(
$search = [
'string' => 'lundi',
'langcode' => $langcode,
'translation' => 'translated',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$this->assertNoText(t('No strings available.'), 'String successfully imported.');
// Ensure the multiline string was imported.
$search = array(
$search = [
'string' => 'Source string for multiline translation',
'langcode' => $langcode,
'translation' => 'all',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$this->assertText('Multiline translation string to make sure that import works with it.', 'String successfully imported.');
// Ensure 'Allowed HTML source string' was imported but the translation for
// 'Another allowed HTML source string' was not because it contains invalid
// HTML.
$search = array(
$search = [
'string' => 'HTML source string',
'langcode' => $langcode,
'translation' => 'all',
);
];
$this->drupalPostForm('admin/config/regional/translate', $search, t('Filter'));
$this->assertText('Allowed HTML source string', 'String successfully imported.');
$this->assertNoText('Another allowed HTML source string', 'String with disallowed translation not imported.');

View file

@ -42,7 +42,7 @@ class TranslationString extends StringBase {
/**
* {@inheritdoc}
*/
public function __construct($values = array()) {
public function __construct($values = []) {
parent::__construct($values);
if (!isset($this->isNew)) {
// We mark the string as not new if it is a complete translation.