You are here

class ContentTranslationPreviewController in Translation Management Tool 8

Content preview translation controller.

Hierarchy

Expanded class hierarchy of ContentTranslationPreviewController

File

sources/content/src/Controller/ContentTranslationPreviewController.php, line 17

Namespace

Drupal\tmgmt_content\Controller
View source
class ContentTranslationPreviewController extends ControllerBase {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Creates an ContentTranslationPreviewController object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager'));
  }

  /**
   * Preview job item entity data.
   *
   * @param \Drupal\tmgmt\JobItemInterface $tmgmt_job_item
   *   Job item to be previewed.
   * @param string $view_mode
   *   The view mode that should be used to display the entity.
   *
   * @return array
   *   A render array.
   */
  public function preview(JobItemInterface $tmgmt_job_item, $view_mode) {

    // Load entity.
    $entity = ContentEntitySource::load($tmgmt_job_item
      ->getItemType(), $tmgmt_job_item
      ->getItemId(), $tmgmt_job_item
      ->getJob()
      ->getSourceLangcode());

    // We cannot show the preview for non-existing entities.
    if (!$entity) {
      throw new NotFoundHttpException();
    }
    $data = $tmgmt_job_item
      ->getData();
    $target_langcode = $tmgmt_job_item
      ->getJob()
      ->getTargetLangcode();

    // Populate preview with target translation data.
    $preview = $this
      ->makePreview($entity, $data, $target_langcode);

    // Set the entity into preview mode.
    $preview->in_preview = TRUE;

    // Build view for entity.
    $page = $this->entityTypeManager
      ->getViewBuilder($entity
      ->getEntityTypeId())
      ->view($preview, $view_mode, $preview
      ->language()
      ->getId());

    // The preview is not cacheable.
    $page['#cache']['max-age'] = 0;
    \Drupal::service('page_cache_kill_switch')
      ->trigger();
    return $page;
  }

  /**
   * The _title_callback for the page that renders a single node in preview.
   *
   * @param \Drupal\tmgmt\JobItemInterface $tmgmt_job_item
   *   The current node.
   *
   * @return string
   *   The page title.
   */
  public function title(JobItemInterface $tmgmt_job_item) {
    $target_language = $tmgmt_job_item
      ->getJob()
      ->getTargetLanguage()
      ->getName();
    $entity = ContentEntitySource::load($tmgmt_job_item
      ->getItemType(), $tmgmt_job_item
      ->getItemId(), $tmgmt_job_item
      ->getJob()
      ->getSourceLangcode());
    $title = $entity
      ->label();
    return t("Preview of @title for @target_language", [
      '@title' => $title,
      '@target_language' => $target_language,
    ]);
  }

  /**
   * Builds the entity translation for the provided translation data.
   *
   * @param \Drupal\Core\Entity\ContentEntityInterface $entity
   *   The entity for which the translation should be returned.
   * @param array $data
   *   The translation data for the fields.
   * @param string $target_langcode
   *   The target language.
   *
   * @return \Drupal\Core\Entity\ContentEntityInterface
   *   Translation data.
   */
  protected function makePreview(ContentEntityInterface $entity, array $data, $target_langcode) {

    // If the translation for this language does not exist yet, initialize it.
    if (!$entity
      ->hasTranslation($target_langcode)) {
      $entity
        ->addTranslation($target_langcode, $entity
        ->toArray());
    }
    $embeded_fields = $this
      ->config('tmgmt_content.settings')
      ->get('embedded_fields');
    $translation = $entity
      ->getTranslation($target_langcode);
    foreach (Element::children($data) as $name) {
      $field_data = $data[$name];
      foreach (Element::children($field_data) as $delta) {
        $field_item = $field_data[$delta];
        foreach (Element::children($field_item) as $property) {
          $property_data = $field_item[$property];

          // If there is translation data for the field property, save it.
          if (isset($property_data['#translation']['#text']) && $property_data['#translate'] && is_numeric($delta)) {
            $item = $translation
              ->get($name)
              ->offsetGet($delta);
            if ($item) {
              $translation
                ->get($name)
                ->offsetGet($delta)
                ->set($property, $property_data['#translation']['#text']);
            }
          }
          elseif (isset($embeded_fields[$entity
            ->getEntityTypeId()][$name])) {
            $this
              ->makePreview($translation
              ->get($name)
              ->offsetGet($delta)->{$property}, $property_data, $target_langcode);
          }
        }
      }
    }
    return $translation;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ContentTranslationPreviewController::$entityTypeManager protected property The entity type manager. Overrides ControllerBase::$entityTypeManager
ContentTranslationPreviewController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
ContentTranslationPreviewController::makePreview protected function Builds the entity translation for the provided translation data.
ContentTranslationPreviewController::preview public function Preview job item entity data.
ContentTranslationPreviewController::title public function The _title_callback for the page that renders a single node in preview.
ContentTranslationPreviewController::__construct public function Creates an ContentTranslationPreviewController object.
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.