translators-8.x-1.x-dev/modules/translators_content/tests/src/Functional/TranslatorsContentTestsTrait.php
modules/translators_content/tests/src/Functional/TranslatorsContentTestsTrait.php
<?php
namespace Drupal\Tests\translators_content\Functional;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Url;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\node\Entity\Node;
/**
* Trait TranslatorsContentTestsTrait.
*
* @package Drupal\Tests\translators_content\Functional
*
* @group translators_content
*/
trait TranslatorsContentTestsTrait {
/**
* Additional steps for tests set up.
* @todo: Delete everywhere it is used
*/
protected function setUpTest() {
}
/**
* Get array of all site languages.
*
* @return array
* All testing langcodes array.
*/
protected function getAllSiteLangcodes() {
return array_keys($this->container->get('language_manager')
->getLanguages(LanguageInterface::STATE_CONFIGURABLE));
}
/**
* Get array of all site languages.
*
* @return array
* All testing langcodes array.
*/
protected function getSiteDefaultLangcode() {
return $this->container->get('language_manager')->getDefaultLanguage()->getId();
}
/**
* Get array of all unregistered languages.
*
* @return array
* All testing langcodes array.
*/
protected function getUnregisteredLangcodes() {
$registered_langcodes = $this->container->get('translators.skills')->getAllLangcodes();
$site_langcodes = $this->getAllSiteLangcodes();
return array_diff($site_langcodes, $registered_langcodes);
}
/**
* Enable filtering translation overview to users translation skills.
*
* @param bool $enable
* An option to enable or disabe this option.
*/
protected function enableFilterTranslationOverviewToSkills($enable = TRUE) {
$this->drupalGet('/admin/config/regional/translators');
$this->submitForm(
['enable_filter_translation_overview_to_skills' => $enable],
'Save configuration'
);
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->pageTextContains('The configuration options have been saved.', FALSE);
\Drupal::configFactory()->clearStaticCache();
}
/**
* Enable always display original language in translation overview.
*
* @param bool $enable
* An option to enable or disabe this option.
*/
protected function enableAlwaysDisplayOriginalLanguageInTranslationOverview($enable = TRUE) {
$this->drupalGet('/admin/config/regional/translators');
$this->submitForm(
['always_display_original_language_translation_overview' => $enable],
'Save configuration'
);
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->pageTextContains('The configuration options have been saved.', FALSE);
\Drupal::configFactory()->clearStaticCache();
}
/**
* Enable preseting source language to the users translation skills.
*
* @param bool $enable
* An option to enable or disabe this option.
*/
protected function enableAutoPresetSourceLanguage($enable = TRUE) {
$this->drupalGet('/admin/config/regional/translators');
$this->submitForm(
['enable_auto_preset_source_language_by_skills' => $enable],
'Save configuration'
);
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->pageTextContains('The configuration options have been saved.', FALSE);
\Drupal::configFactory()->clearStaticCache();
}
/**
* Enable strict translation skill pairing.
*
* @param bool $enable
* An option to enable or disabe this option.
*/
protected function enableStrictTranslationSkillsPairing($enable = TRUE) {
$this->drupalGet('/admin/config/regional/translators');
$this->submitForm(
['enable_strict_translation_skill_pairing' => $enable],
'Save configuration'
);
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->pageTextContains('The configuration options have been saved.', FALSE);
\Drupal::configFactory()->clearStaticCache();
}
/**
* Change language settings for entity types.
*
* @param string $category
* Entity category (e.g. node).
* @param string $subcategory
* Entity subcategory (e.g. article).
*/
protected function enableTranslation($category, $subcategory) {
$this->drupalGet('admin/config/regional/content-language');
$this->submitForm([
"entity_types[$category]" => 1,
"settings[$category][$subcategory][translatable]" => 1,
"settings[$category][$subcategory][settings][language][language_alterable]" => 1,
], 'Save configuration');
$this->container->get('entity_type.manager')->clearCachedDefinitions();
}
/**
* Create additional languages for testing.
*/
protected function createLanguages(array $langcodes) {
try {
foreach ($langcodes as $langcode) {
if ($langcode === $this->getSiteDefaultLangcode()) {
continue;
}
$this->assertEquals(1, ConfigurableLanguage::createFromLangcode($langcode)->save());
}
}
catch (EntityStorageException $e) {
$this->fail('Additional languages have not been created');
}
}
/**
* Add translation skill.
*
* @param array $skill
* Array of arrays of source->target skills.
*/
public function addSkill(array $skill) {
$user = $this->container->get('current_user');
$user_id = $user->id();
$user = $this->loadUser($user_id);
$translationSkillsField = \Drupal::configFactory()
->get('translators.settings')
->get('translation_skills_field_name');
$user->get($translationSkillsField)->appendItem([
'language_source' => $skill[0],
'language_target' => $skill[1],
]);
$user->save();
$this->container->get('entity_type.manager')->getStorage('user')->resetCache([$user_id]);
foreach ($skill as $langcode) {
$this->assertTrue($this->container->get('translators.skills')->hasLangcode($langcode));
}
}
/**
* Remove all translation skill.
*/
public function removeSkills() {
$user = $this->container->get('current_user');
$user_id = $user->id();
$user = $this->loadUser($user_id);
$translationSkillsField = \Drupal::configFactory()
->get('translators.settings')
->get('translation_skills_field_name');
$user->get($translationSkillsField)->setValue([]);
$user->save();
$this->container->get('entity_type.manager')->getStorage('user')->resetCache([$user_id]);
}
/**
* Load user entity by a given ID.
*
* @param int|string $id
* User ID.
*
* @return \Drupal\user\UserInterface|null
* Loaded user entity or NULL.
*/
protected function loadUser($id) {
$this->container->get('entity_type.manager')->getStorage('user')->resetCache([$id]);
return $this->container->get('entity_type.manager')->getStorage('user')->load($id);
}
/**
* Add all translations to an entity.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity to be translated.
*/
public function addAllEntityTranslations(EntityInterface $entity) {
foreach ($this->getAllSiteLangcodes() as $langcode) {
if ($langcode == $entity->getUntranslated()->language()->getId()) {
continue;
}
$this->addEntityTranslation($entity, $langcode);
}
}
/**
* Assert if option is NOT available in select list.
*
* @param string $field_name
* The field machine name.
* @param string $value
* The value to be checked for.
*/
public function assertOptionNotAvailable($field_name, $value) {
$this->assertOptionAvailable($field_name, $value, FALSE);
}
/**
* Assert if option is available in select list.
*
* @param string $field_name
* The field machine name.
* @param string $value
* The value to be asserted.
* @param string $assert_true
* Assert TRUE or FALSE. Optional, defaults to TRUE.
*/
public function assertOptionAvailable($field_name, $value, $assert_true = TRUE) {
$options = $this->getOptionValues($field_name);
if ($assert_true) {
$this->assertContains($value, $options);
}
else {
$this->assertNotContains($value, $options);
}
}
/**
* Assert count of options in select list.
*
* @param string $field_name
* The field machine name.
* @param int $number
* The number to be asserted.
*/
public function assertOptionCount($field_name, int $number) {
$options = $this->getOptionValues($field_name);
$this->assertCount($number, $options);
}
/**
* Assert count of options in select list.
*
* @param string $field_name
* The field machine name.
*/
public function getOptionValues($field_name) {
// Find the field element.
$field = $this->getSession()
->getPage()
->findField($field_name);
$this->assertNotNull($field);
// Get all existing options of the field.
$options = $field->findAll('xpath', '//option');
$this->assertNotNull($options);
// Return array of options' values.
return array_map(function ($option) {
return $option->getAttribute('value') ?: $option->getText();
}, $options);
}
/**
* Assert if any matching element contains string.
*
* @param string $selectorType
* Selector type machine name.
* @param string $selector
* The selector to look for.
* @param string $html
* The string to look for inside all selected elements.
*/
public function assertAnyElementContains(string $selectorType, string $selector, string $html) {
$this->assertSession()->elementExists($selectorType, $selector);
$elements = $this->getSession()
->getPage()
->findAll($selectorType, $selector);
foreach ($elements as $element) {
$actual = $element->getHtml();
if (strpos($actual, $html) !== FALSE) {
return;
}
}
$this->assertSession()->elementContains($selectorType, $selector, $html);
}
/**
* Assert if none matching element contains string.
*
* @param string $selectorType
* Selector type machine name.
* @param string $selector
* The selector to look for.
* @param string $html
* The string to look for inside all selected elements.
*/
public function assertNoneElementContains(string $selectorType, string $selector, string $html) {
$this->assertSession()->elementExists($selectorType, $selector);
$elements = $this->getSession()
->getPage()
->findAll($selectorType, $selector);
foreach ($elements as $element) {
$actual = $element->getHtml();
if (strpos($actual, $html) !== FALSE) {
$this->assertSession()->elementNotContains($selectorType, $selector, $html);
}
}
}
/**
* Get entity translation.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity to be translated.
* @param string $langcode
* Language ID.
*/
public function drupalGetEntity(EntityInterface $entity, $langcode = NULL) {
$langcode = !empty($langcode) ? $langcode : $entity->getUntranslated()->language()->getId();
$entity = $entity->getTranslation($langcode);
$language_manager = $this->container->get('language_manager');
$options = ['language' => $language_manager->getLanguage($langcode)];
$this->drupalGet($entity->toUrl('canonical', $options));
}
/**
* Get create entity translation form url.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity to be translated.
* @param string $source
* Source language ID.
* @param string $target
* Target language ID.
*
* @return \Drupal\Core\Url
* URL object for creating enitity translation.
*/
public function getCreateEntityTranslationUrl(EntityInterface $entity, $source, $target) {
$language_manager = $this->container->get('language_manager');
$entityTypeId = $entity->getEntityTypeId();
return Url::fromRoute(
"entity.$entityTypeId.content_translation_add",
[
$entityTypeId => $entity->id(),
'source' => $source,
'target' => $target,
],
[
'language' => $language_manager->getLanguage($target),
]
);
}
/**
* Get entity translation form url.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity to be translated.
* @param string $langcode
* Language ID.
* @param string $operation
* Operation ID.
*
* @return \Drupal\Core\Url
* URL object for enitity translation operation.
*/
public function getEntityTranslationOperationUrl(EntityInterface $entity, $langcode, $operation) {
$entity = $entity->getTranslation($langcode);
$languages = $this->container->get('language_manager')->getLanguages();
$options = ['language' => $languages[$langcode]];
return $entity->toUrl("$operation-form", $options);
}
/**
* Get current path.
*
* @return string
* Current path.
*/
public function getCurrentPath($langcode = NULL) {
$baseUrl = $this->baseUrl;
$fullUrl = $this->getUrl();
$path = str_replace($baseUrl, "", $fullUrl);
if (empty($langcode) || $langcode == $this->getSiteDefaultLangcode()) {
return $path;
}
return "/$langcode" . $path;
}
/**
* Create test node.
*
* @param null|string $langcode
* Optional. Default language ID.
* @param null|int $uid
* Optional. Author ID.
*/
public function createTestNode($langcode = NULL, int $uid = NULL) {
$langcode = !empty($langcode) ? $langcode : $this->getSiteDefaultLangcode();
$uid = !empty($uid) ? $uid : \Drupal::currentUser()->id();
$bundle = isset($this->bundle) ? $this->bundle : 'article';
$node = Node::create([
'type' => $bundle,
'title' => $this->randomString(),
'langcode' => $langcode,
'uid' => $uid,
'status' => 1,
]);
$node->save();
return $node;
}
/**
* Add a translation to an node.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity to be translated.
* @param null|string $target
* Optional. Target language ID.
* @param null|string $source
* Optional. Source language ID.
*/
public function addNodeTranslation(EntityInterface $entity, $target, $source = NULL) {
$source = !empty($source) ? $source : $entity->getUntranslated()->language()->getId();
$translation_add_url = $this->getCreateEntityTranslationUrl($entity, $source, $target);
$this->drupalGet($translation_add_url);
$this->assertSession()->statusCodeEquals(200);
$this->submitForm([], t('Save (this translation)'));
$this->rebuildContainer();
}
/**
* Add all translations to a node.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity to be translated.
*/
public function addAllNodeTranslations(EntityInterface $entity) {
foreach ($this->getAllSiteLangcodes() as $langcode) {
if ($langcode == $entity->getUntranslated()->language()->getId()) {
continue;
}
$this->addNodeTranslation($entity, $langcode);
}
}
}
