View source
<?php
namespace Drupal\entity_translation_unified_form;
use Drupal\node\Entity\Node;
class EtufHelper {
public static function addMessage($message) {
\Drupal::messenger()
->addMessage($message);
}
public static function addToLog($message, $debug = FALSE) {
if ($debug) {
\Drupal::logger('etuf')
->notice($message);
}
}
public static function getLang() {
return \Drupal::languageManager()
->getCurrentLanguage()
->getId();
}
public static function getOtherEnabledLanguages() {
$language = \Drupal::languageManager()
->getCurrentLanguage();
$languages = \Drupal::languageManager()
->getLanguages();
$other_languages = [];
foreach ($languages as $field_language_code => $field_language) {
if ($field_language_code != $language
->getId()) {
$other_languages[$field_language_code] = $field_language
->getName();
}
}
return $other_languages;
}
public static function getDefaultLangcode() {
$language = \Drupal::languageManager()
->getDefaultLanguage();
return $language
->getId();
}
public static function postCreateOrUpdateAutoTranslate($entity_id, $other_lang) {
$menu_link_main_array = static::translateLinkIfNotTranslated($entity_id, $other_lang);
return $menu_link_main_array;
}
public static function translateLinkIfNotTranslated($nid, $other_lang) {
$menu_link_ids = [];
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$result = $menu_link_manager
->loadLinksByRoute('entity.node.canonical', [
'node' => $nid,
]);
$node = NULL;
foreach ($result as $menu_item) {
if (is_object($menu_item)) {
$id = $menu_item
->getPluginDefinition()['metadata']['entity_id'];
$menu_link = \Drupal::entityTypeManager()
->getStorage('menu_link_content')
->load($id);
if (!$menu_link
->hasTranslation($other_lang)) {
$node = Node::load($nid);
if (isset($node) && !is_null($node)) {
if ($node
->hasTranslation($other_lang)) {
$title = $node
->getTranslation($other_lang)
->getTitle();
$menu_link
->addTranslation($other_lang, [
'title' => $title,
]);
$menu_link
->save();
$menu_link_ids[] = $id;
$logmsg = t('Translated menu link mlid:@mlid for nid:@nid', [
'@mlid' => $id,
'@nid' => $nid,
]);
static::addToLog($logmsg, TRUE);
}
}
}
}
}
return $menu_link_ids;
}
}