function LocaleTranslationTest::testJavaScriptTranslation

File

drupal/core/modules/locale/lib/Drupal/locale/Tests/LocaleTranslationTest.php, line 215
Definition of Drupal\locale\Tests\LocaleTranslationTest.

Class

LocaleTranslationTest
Functional test for string translation and validation.

Namespace

Drupal\locale\Tests

Code

function testJavaScriptTranslation() {
  $user = $this
    ->drupalCreateUser(array(
    'translate interface',
    'administer languages',
    'access administration pages',
  ));
  $this
    ->drupalLogin($user);
  $config = config('locale.settings');
  $langcode = 'xx';

  // The English name for the language. This will be translated.
  $name = $this
    ->randomName(16);

  // Add custom language.
  $edit = array(
    'predefined_langcode' => 'custom',
    'langcode' => $langcode,
    'name' => $name,
    'direction' => '0',
  );
  $this
    ->drupalPost('admin/config/regional/language/add', $edit, t('Add custom language'));
  drupal_static_reset('language_list');

  // Build the JavaScript translation file.
  // Retrieve the source string of the first string available in the
  // {locales_source} table and translate it.
  $source = db_select('locales_source', 'l')
    ->fields('l', array(
    'source',
  ))
    ->condition('l.source', '%.js%', 'LIKE')
    ->range(0, 1)
    ->execute()
    ->fetchField();
  $search = array(
    'string' => $source,
    'langcode' => $langcode,
    'translation' => 'all',
  );
  $this
    ->drupalPost('admin/config/regional/translate/translate', $search, t('Filter'));
  $textarea = current($this
    ->xpath('//textarea'));
  $lid = (string) $textarea[0]['name'];
  $edit = array(
    $lid => $this
      ->randomName(),
  );
  $this
    ->drupalPost('admin/config/regional/translate/translate', $edit, t('Save translations'));

  // Trigger JavaScript translation parsing and building.
  _locale_rebuild_js($langcode);
  $locale_javascripts = \Drupal::state()
    ->get('locale.translation.javascript') ?: array();
  $js_file = 'public://' . $config
    ->get('javascript.directory') . '/' . $langcode . '_' . $locale_javascripts[$langcode] . '.js';
  $this
    ->assertTrue($result = file_exists($js_file), t('JavaScript file created: %file', array(
    '%file' => $result ? $js_file : t('not found'),
  )));

  // Test JavaScript translation rebuilding.
  file_unmanaged_delete($js_file);
  $this
    ->assertTrue($result = !file_exists($js_file), t('JavaScript file deleted: %file', array(
    '%file' => $result ? $js_file : t('found'),
  )));
  cache_invalidate_tags(array(
    'content' => TRUE,
  ));
  _locale_rebuild_js($langcode);
  $this
    ->assertTrue($result = file_exists($js_file), t('JavaScript file rebuilt: %file', array(
    '%file' => $result ? $js_file : t('not found'),
  )));
}