TranslationLanguageRenderer.php 2.35 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Contains \Drupal\views\Entity\Render\TranslationLanguageRenderer.
 */

namespace Drupal\views\Entity\Render;

10
use Drupal\Core\Language\LanguageInterface;
11 12 13 14
use Drupal\views\Plugin\views\query\QueryPluginBase;
use Drupal\views\ResultRow;

/**
15
 * Renders entity translations in their row language.
16
 */
17
class TranslationLanguageRenderer extends EntityTranslationRendererBase {
18 19 20 21 22 23 24 25 26 27 28

  /**
   * Stores the field alias of the langcode column.
   *
   * @var string
   */
  protected $langcodeAlias;

  /**
   * {@inheritdoc}
   */
29
  public function query(QueryPluginBase $query, $relationship = NULL) {
30 31 32 33
    // In order to render in the translation language of the entity, we need
    // to add the language code of the entity to the query. Skip if the site
    // is not multilingual or the entity is not translatable.
    if (!$this->languageManager->isMultilingual() || !$this->entityType->hasKey('langcode')) {
34 35
      return;
    }
36
    $langcode_key = $this->entityType->getKey('langcode');
37 38 39 40 41
    $storage = \Drupal::entityManager()->getStorage($this->entityType->id());

    if ($table = $storage->getTableMapping()->getFieldTableName($langcode_key)) {
      $table_alias = $query->ensureTable($table, $relationship);
      $this->langcodeAlias = $query->addField($table_alias, $langcode_key);
42 43 44
    }
  }

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
  /**
   * {@inheritdoc}
   */
  public function preRender(array $result) {
    $view_builder = $this->view->rowPlugin->entityManager->getViewBuilder($this->entityType->id());

    /** @var \Drupal\views\ResultRow $row */
    foreach ($result as $row) {
      $entity = $row->_entity;
      $entity->view = $this->view;
      $langcode = $this->getLangcode($row);
      $this->build[$entity->id()][$langcode] = $view_builder->view($entity, $this->view->rowPlugin->options['view_mode'], $this->getLangcode($row));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function render(ResultRow $row) {
    $entity_id = $row->_entity->id();
    $langcode = $this->getLangcode($row);
    return $this->build[$entity_id][$langcode];
  }

69 70 71
  /**
   * {@inheritdoc}
   */
72
  public function getLangcode(ResultRow $row) {
73
    return isset($row->{$this->langcodeAlias}) ? $row->{$this->langcodeAlias} : $this->languageManager->getDefaultLanguage()->getId();
74 75
  }

76 77 78 79 80 81
  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    return ['languages:' . LanguageInterface::TYPE_CONTENT];
  }
82
}