View source
<?php
namespace Drupal\Tests\language\Functional;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Url;
use Drupal\file\Entity\File;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationBrowser;
use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationSelected;
use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationSession;
use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl;
use Drupal\Tests\BrowserTestBase;
use Drupal\user\Plugin\LanguageNegotiation\LanguageNegotiationUser;
use Drupal\user\Plugin\LanguageNegotiation\LanguageNegotiationUserAdmin;
use Drupal\Core\Language\Language;
use Drupal\Core\Language\LanguageInterface;
use Symfony\Component\HttpFoundation\Request;
use Drupal\language\LanguageNegotiatorInterface;
use Drupal\block\Entity\Block;
class LanguageUILanguageNegotiationTest extends BrowserTestBase {
protected $adminUser;
protected static $modules = [
'locale',
'language_test',
'block',
'user',
'content_translation',
];
protected $defaultTheme = 'stark';
protected function setUp() : void {
parent::setUp();
$this->adminUser = $this
->drupalCreateUser([
'administer languages',
'translate interface',
'access administration pages',
'administer blocks',
]);
$this
->drupalLogin($this->adminUser);
}
public function testUILanguageNegotiation() {
$langcode_unknown = 'blah-blah';
$langcode_browser_fallback = 'vi';
$langcode = 'zh-hans';
$http_header_browser_fallback = [
"Accept-Language" => "{$langcode_browser_fallback};q=1",
];
$http_header_blah = [
"Accept-Language" => "blah;q=1",
];
\Drupal::service('file_system')
->mkdir($this->privateFilesDirectory . '/test');
$filepath = 'private://test/private-file-test.txt';
$contents = "file_put_contents() doesn't seem to appreciate empty strings so let's put in some data.";
file_put_contents($filepath, $contents);
$file = File::create([
'uri' => $filepath,
'uid' => $this->adminUser
->id(),
]);
$file
->save();
$default_language = \Drupal::languageManager()
->getDefaultLanguage();
ConfigurableLanguage::createFromLangcode($langcode_browser_fallback)
->save();
$this
->config('system.site')
->set('default_langcode', $langcode_browser_fallback)
->save();
ConfigurableLanguage::createFromLangcode($langcode)
->save();
$default_string = 'Hide descriptions';
$this
->drupalGet('admin/config');
$this
->config('system.site')
->set('default_langcode', $default_language
->getId())
->save();
$this
->config('language.negotiation')
->set('url.prefixes.en', '')
->save();
$this
->rebuildContainer();
$language_browser_fallback_string = "In {$langcode_browser_fallback} In {$langcode_browser_fallback} In {$langcode_browser_fallback}";
$language_string = "In {$langcode} In {$langcode} In {$langcode}";
$search = [
'string' => $default_string,
'langcode' => $langcode_browser_fallback,
];
$this
->drupalGet('admin/config/regional/translate');
$this
->submitForm($search, 'Filter');
$textarea = $this
->assertSession()
->elementExists('xpath', '//textarea');
$lid = $textarea
->getAttribute('name');
$edit = [
$lid => $language_browser_fallback_string,
];
$this
->drupalGet('admin/config/regional/translate');
$this
->submitForm($edit, 'Save translations');
$search = [
'string' => $default_string,
'langcode' => $langcode,
];
$this
->drupalGet('admin/config/regional/translate');
$this
->submitForm($search, 'Filter');
$textarea = $this
->assertSession()
->elementExists('xpath', '//textarea');
$lid = $textarea
->getAttribute('name');
$edit = [
$lid => $language_string,
];
$this
->drupalGet('admin/config/regional/translate');
$this
->submitForm($edit, 'Save translations');
$edit = [
'selected_langcode' => $langcode,
];
$this
->drupalGet('admin/config/regional/language/detection/selected');
$this
->submitForm($edit, 'Save configuration');
$test = [
'language_negotiation' => [
LanguageNegotiationSelected::METHOD_ID,
],
'path' => 'admin/config',
'expect' => $language_string,
'expected_method_id' => LanguageNegotiationSelected::METHOD_ID,
'http_header' => $http_header_browser_fallback,
'message' => 'SELECTED: UI language is switched based on selected language.',
];
$this
->doRunTest($test);
$this
->config('language.negotiation')
->set('selected_langcode', NULL)
->save();
$test = [
'language_negotiation' => [
LanguageNegotiationSelected::METHOD_ID,
],
'path' => 'admin/config',
'expect' => $default_string,
'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
'http_header' => $http_header_browser_fallback,
'message' => 'SELECTED > DEFAULT: UI language is switched based on selected language.',
];
$this
->doRunTest($test);
$this
->config('language.negotiation')
->set('selected_langcode', $langcode_unknown)
->save();
$test = [
'language_negotiation' => [
LanguageNegotiationSelected::METHOD_ID,
],
'path' => 'admin/config',
'expect' => $default_string,
'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
'http_header' => $http_header_browser_fallback,
'message' => 'SELECTED > DEFAULT: UI language is switched based on selected language.',
];
$this
->doRunTest($test);
$tests = [
[
'language_negotiation' => [
LanguageNegotiationUrl::METHOD_ID,
LanguageNegotiationSelected::METHOD_ID,
],
'path' => 'admin/config',
'expect' => $default_string,
'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
'http_header' => $http_header_browser_fallback,
'message' => 'URL (PATH) > DEFAULT: no language prefix, UI language is default and the browser language preference setting is not used.',
],
[
'language_negotiation' => [
LanguageNegotiationUrl::METHOD_ID,
LanguageNegotiationSelected::METHOD_ID,
],
'path' => "{$langcode}/admin/config",
'expect' => $language_string,
'expected_method_id' => LanguageNegotiationUrl::METHOD_ID,
'http_header' => $http_header_browser_fallback,
'message' => 'URL (PATH) > DEFAULT: with language prefix, UI language is switched based on path prefix',
],
[
'language_negotiation' => [
LanguageNegotiationUrl::METHOD_ID,
LanguageNegotiationBrowser::METHOD_ID,
],
'path' => 'admin/config',
'expect' => $language_browser_fallback_string,
'expected_method_id' => LanguageNegotiationBrowser::METHOD_ID,
'http_header' => $http_header_browser_fallback,
'message' => 'URL (PATH) > BROWSER: no language prefix, UI language is determined by browser language preference',
],
[
'language_negotiation' => [
LanguageNegotiationUrl::METHOD_ID,
LanguageNegotiationBrowser::METHOD_ID,
],
'path' => "{$langcode}/admin/config",
'expect' => $language_string,
'expected_method_id' => LanguageNegotiationUrl::METHOD_ID,
'http_header' => $http_header_browser_fallback,
'message' => 'URL (PATH) > BROWSER: with language prefix, UI language is based on path prefix',
],
[
'language_negotiation' => [
LanguageNegotiationUrl::METHOD_ID,
LanguageNegotiationBrowser::METHOD_ID,
LanguageNegotiationSelected::METHOD_ID,
],
'path' => 'admin/config',
'expect' => $default_string,
'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
'http_header' => $http_header_blah,
'message' => 'URL (PATH) > BROWSER > DEFAULT: no language prefix and browser language preference set to unknown language should use default language',
],
];
foreach ($tests as $test) {
$this
->doRunTest($test);
}
$definitions = \Drupal::languageManager()
->getNegotiator()
->getNegotiationMethods();
$language_interface_method_definitions = array_filter($definitions, function ($method_definition) {
return !isset($method_definition['types']) || isset($method_definition['types']) && in_array(LanguageInterface::TYPE_INTERFACE, $method_definition['types']);
});
$this
->config('language.types')
->set('negotiation.' . LanguageInterface::TYPE_INTERFACE . '.enabled', array_flip(array_keys($language_interface_method_definitions)))
->save();
$this
->drupalGet("{$langcode_unknown}/admin/config", [], $http_header_browser_fallback);
$this
->assertSession()
->statusCodeEquals(404);
$account = $this->loggedInUser;
$account->preferred_langcode = NULL;
$account
->save();
$test = [
'language_negotiation' => [
LanguageNegotiationUser::METHOD_ID,
LanguageNegotiationSelected::METHOD_ID,
],
'path' => 'admin/config',
'expect' => $default_string,
'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
'http_header' => [],
'message' => 'USER > DEFAULT: no preferred user language setting, the UI language is default',
];
$this
->doRunTest($test);
$account = $this->loggedInUser;
$account->preferred_langcode = $default_language
->getId();
$account
->save();
$test = [
'language_negotiation' => [
LanguageNegotiationUser::METHOD_ID,
LanguageNegotiationUrl::METHOD_ID,
],
'path' => "{$langcode}/admin/config",
'expect' => $default_string,
'expected_method_id' => LanguageNegotiationUser::METHOD_ID,
'http_header' => [],
'message' => 'USER > URL: User has default language as preferred user language setting, the UI language is default',
];
$this
->doRunTest($test);
$account = $this->loggedInUser;
$account->preferred_langcode = $langcode_unknown;
$account
->save();
$test = [
'language_negotiation' => [
LanguageNegotiationUser::METHOD_ID,
LanguageNegotiationSelected::METHOD_ID,
],
'path' => 'admin/config',
'expect' => $default_string,
'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
'http_header' => [],
'message' => 'USER > DEFAULT: invalid preferred user language setting, the UI language is default',
];
$this
->doRunTest($test);
$account->preferred_langcode = $langcode;
$account
->save();
$test = [
'language_negotiation' => [
LanguageNegotiationUser::METHOD_ID,
LanguageNegotiationSelected::METHOD_ID,
],
'path' => 'admin/config',
'expect' => $language_string,
'expected_method_id' => LanguageNegotiationUser::METHOD_ID,
'http_header' => [],
'message' => 'USER > DEFAULT: defined preferred user language setting, the UI language is based on user setting',
];
$this
->doRunTest($test);
$account->preferred_admin_langcode = NULL;
$account
->save();
$test = [
'language_negotiation' => [
LanguageNegotiationUserAdmin::METHOD_ID,
LanguageNegotiationSelected::METHOD_ID,
],
'path' => 'admin/config',
'expect' => $default_string,
'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
'http_header' => [],
'message' => 'USER ADMIN > DEFAULT: no preferred user admin language setting, the UI language is default',
];
$this
->doRunTest($test);
$account->preferred_admin_langcode = $langcode_unknown;
$account
->save();
$test = [
'language_negotiation' => [
LanguageNegotiationUserAdmin::METHOD_ID,
LanguageNegotiationSelected::METHOD_ID,
],
'path' => 'admin/config',
'expect' => $default_string,
'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
'http_header' => [],
'message' => 'USER ADMIN > DEFAULT: invalid preferred user admin language setting, the UI language is default',
];
$this
->doRunTest($test);
$account->preferred_admin_langcode = $langcode;
$account
->save();
$test = [
'language_negotiation' => [
LanguageNegotiationUserAdmin::METHOD_ID,
LanguageNegotiationSelected::METHOD_ID,
],
'path' => 'admin/config',
'expect' => $language_string,
'expected_method_id' => LanguageNegotiationUserAdmin::METHOD_ID,
'http_header' => [],
'message' => 'USER ADMIN > DEFAULT: defined preferred user admin language setting, the UI language is based on user setting',
];
$this
->doRunTest($test);
$language_negotiation_session_param = $this
->randomMachineName();
$edit = [
'language_negotiation_session_param' => $language_negotiation_session_param,
];
$this
->drupalGet('admin/config/regional/language/detection/session');
$this
->submitForm($edit, 'Save configuration');
$tests = [
[
'language_negotiation' => [
LanguageNegotiationSession::METHOD_ID,
],
'path' => "admin/config",
'expect' => $default_string,
'expected_method_id' => LanguageNegotiatorInterface::METHOD_ID,
'http_header' => $http_header_browser_fallback,
'message' => 'SESSION > DEFAULT: no language given, the UI language is default',
],
[
'language_negotiation' => [
LanguageNegotiationSession::METHOD_ID,
],
'path' => 'admin/config',
'path_options' => [
'query' => [
$language_negotiation_session_param => $langcode,
],
],
'expect' => $language_string,
'expected_method_id' => LanguageNegotiationSession::METHOD_ID,
'http_header' => $http_header_browser_fallback,
'message' => 'SESSION > DEFAULT: language given, UI language is determined by session language preference',
],
];
foreach ($tests as $test) {
$this
->doRunTest($test);
}
}
protected function doRunTest($test) {
$test += [
'path_options' => [],
];
if (!empty($test['language_negotiation'])) {
$method_weights = array_flip($test['language_negotiation']);
$this->container
->get('language_negotiator')
->saveConfiguration(LanguageInterface::TYPE_INTERFACE, $method_weights);
}
if (!empty($test['language_negotiation_url_part'])) {
$this
->config('language.negotiation')
->set('url.source', $test['language_negotiation_url_part'])
->save();
}
if (!empty($test['language_test_domain'])) {
\Drupal::state()
->set('language_test.domain', $test['language_test_domain']);
}
$this->container
->get('language_manager')
->reset();
$this
->drupalGet($test['path'], $test['path_options'], $test['http_header']);
$this
->assertSession()
->pageTextContains($test['expect']);
$this
->assertSession()
->statusMessageContains('Language negotiation method: ' . $test['expected_method_id'], 'status');
Cache::invalidateTags([
'route_match',
]);
$this
->drupalGet('system/files/test/private-file-test.txt');
$this
->assertSession()
->statusCodeEquals(200);
}
public function testUrlLanguageFallback() {
$langcode_browser_fallback = 'it';
ConfigurableLanguage::createFromLangcode($langcode_browser_fallback)
->save();
$languages = $this->container
->get('language_manager')
->getLanguages();
$edit = [
'prefix[en]' => 'en',
];
$this
->drupalGet('admin/config/regional/language/detection/url');
$this
->submitForm($edit, 'Save configuration');
$edit = [
'language_interface[enabled][language-browser]' => TRUE,
'language_interface[enabled][language-url]' => TRUE,
'language_interface[weight][language-browser]' => -8,
'language_interface[weight][language-url]' => -10,
];
$this
->drupalGet('admin/config/regional/language/detection');
$this
->submitForm($edit, 'Save settings');
$this
->drupalGet('admin/config/regional/language/detection');
$this
->drupalPlaceBlock('language_block:' . LanguageInterface::TYPE_INTERFACE, [
'id' => 'test_language_block',
]);
$this
->drupalLogout();
$this
->drupalPlaceBlock('system_branding_block', [
'region' => 'header',
'id' => 'site-branding',
]);
$http_header = [
"Accept-Language" => "{$langcode_browser_fallback};q=1",
];
$language = new Language([
'id' => '',
]);
$this
->drupalGet('', [
'language' => $language,
], $http_header);
$href = Url::fromRoute('<front>')
->toString() . $langcode_browser_fallback;
$this
->assertSession()
->elementTextEquals('xpath', "//div[@id='block-test-language-block']//a[@class='language-link is-active' and starts-with(@href, '{$href}')]", $languages[$langcode_browser_fallback]
->getName());
$this
->assertSession()
->elementTextEquals('xpath', "//div[@id='block-site-branding']/a[@rel='home' and @href='{$href}'][2]", 'Drupal');
}
public function testLanguageDomain() {
global $base_url;
$base_url_host = parse_url($base_url, PHP_URL_HOST);
ConfigurableLanguage::createFromLangcode('it')
->save();
$languages = $this->container
->get('language_manager')
->getLanguages();
$edit = [
'language_interface[enabled][language-url]' => TRUE,
'language_interface[weight][language-url]' => -10,
];
$this
->drupalGet('admin/config/regional/language/detection');
$this
->submitForm($edit, 'Save settings');
$edit = [
'language_negotiation_url_part' => LanguageNegotiationUrl::CONFIG_DOMAIN,
'domain[en]' => '',
];
$this
->drupalGet('admin/config/regional/language/detection/url');
$this
->submitForm($edit, 'Save configuration');
$this
->assertSession()
->statusMessageContains('The domain may not be left blank for English', 'error');
$this
->rebuildContainer();
$edit = [
'language_negotiation_url_part' => LanguageNegotiationUrl::CONFIG_DOMAIN,
'domain[en]' => $base_url_host,
'domain[it]' => 'it.example.com',
];
$this
->drupalGet('admin/config/regional/language/detection/url');
$this
->submitForm($edit, 'Save configuration');
$this
->assertSession()
->statusMessageContains('The configuration options have been saved', 'status');
$this
->rebuildContainer();
$edit = [
'language_negotiation_url_part' => LanguageNegotiationUrl::CONFIG_DOMAIN,
'domain[en]' => $base_url_host,
'domain[it]' => 'it.example.com/',
];
$this
->drupalGet('admin/config/regional/language/detection/url');
$this
->submitForm($edit, 'Save configuration');
$this
->assertSession()
->statusMessageContains("The domain for Italian may only contain the domain name, not a trailing slash, protocol and/or port.", 'error');
$link = 'it.example.com' . rtrim(base_path(), '/') . '/admin';
$italian_url = Url::fromRoute('system.admin', [], [
'language' => $languages['it'],
])
->toString();
$url_scheme = \Drupal::request()
->isSecure() ? 'https://' : 'http://';
$correct_link = $url_scheme . $link;
$this
->assertEquals($correct_link, $italian_url, new FormattableMarkup('The right URL (@url) in accordance with the chosen language', [
'@url' => $italian_url,
]));
$italian_url = Url::fromRoute('system.admin', [], [
'https' => TRUE,
'language' => $languages['it'],
])
->toString();
$correct_link = 'https://' . $link;
$this
->assertSame($correct_link, $italian_url, new FormattableMarkup('The right HTTPS URL (via options) (@url) in accordance with the chosen language', [
'@url' => $italian_url,
]));
$request = Request::create('', 'GET', [], [], [], [
'HTTPS' => 'on',
]);
$this->container
->get('request_stack')
->push($request);
$italian_url = Url::fromRoute('system.admin', [], [
'language' => $languages['it'],
])
->toString();
$correct_link = 'https://' . $link;
$this
->assertSame($correct_link, $italian_url, new FormattableMarkup('The right URL (via current URL scheme) (@url) in accordance with the chosen language', [
'@url' => $italian_url,
]));
}
public function testContentCustomization() {
$edit = [
'language_content[configurable]' => TRUE,
'language_content[enabled][language-url]' => FALSE,
'language_content[enabled][language-session]' => TRUE,
];
$this
->drupalGet('admin/config/regional/language/detection');
$this
->submitForm($edit, 'Save settings');
$config = $this
->config('language.types');
$this
->assertContains('language_interface', $config
->get('configurable'), 'Interface language is configurable.');
$this
->assertContains('language_content', $config
->get('configurable'), 'Content language is configurable.');
$this
->assertArrayNotHasKey('language-url', $config
->get('negotiation.language_content.enabled'));
$this
->assertArrayHasKey('language-session', $config
->get('negotiation.language_content.enabled'));
}
public function testDisableLanguageSwitcher() {
$block_id = 'test_language_block';
$this
->drupalPlaceBlock('language_block:' . LanguageInterface::TYPE_CONTENT, [
'id' => $block_id,
]);
$block = Block::load($block_id);
$this
->assertNotEmpty($block, 'Language switcher block was created.');
$edit = [
'language_content[configurable]' => FALSE,
];
$this
->drupalGet('admin/config/regional/language/detection');
$this
->submitForm($edit, 'Save settings');
$this
->assertSession()
->statusCodeEquals(200);
$block = Block::load($block_id);
$this
->assertNull($block, 'Language switcher block was removed.');
}
}