CommentViewBuilder.php 9.06 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Definition of Drupal\comment\CommentViewBuilder.
6 7 8 9
 */

namespace Drupal\comment;

10
use Drupal\Core\Access\CsrfTokenGenerator;
11
use Drupal\Core\Entity\EntityControllerInterface;
12
use Drupal\Core\Entity\EntityInterface;
13
use Drupal\Core\Entity\EntityManagerInterface;
14
use Drupal\Core\Entity\EntityViewBuilderInterface;
15
use Drupal\Core\Extension\ModuleHandlerInterface;
16
use Drupal\Core\Entity\EntityViewBuilder;
17
use Drupal\entity\Entity\EntityDisplay;
18 19
use Drupal\field\FieldInfo;
use Symfony\Component\DependencyInjection\ContainerInterface;
20 21 22 23

/**
 * Render controller for comments.
 */
24
class CommentViewBuilder extends EntityViewBuilder implements EntityViewBuilderInterface, EntityControllerInterface {
25

26 27 28 29 30 31 32
  /**
   * The entity manager service.
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface
   */
  protected $entityManager;

33 34 35 36 37 38 39 40 41 42 43 44 45 46
  /**
   * The field info service.
   *
   * @var \Drupal\field\FieldInfo
   */
  protected $fieldInfo;

  /**
   * The module handler service.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

47 48 49 50 51 52 53
  /**
   * The CSRF token manager service.
   *
   * @var \Drupal\Core\Access\CsrfTokenGenerator
   */
  protected $csrfToken;

54 55 56 57 58 59 60 61
  /**
   * {@inheritdoc}
   */
  public static function createInstance(ContainerInterface $container, $entity_type, array $entity_info) {
    return new static(
      $entity_type,
      $container->get('entity.manager'),
      $container->get('field.info'),
62 63
      $container->get('module_handler'),
      $container->get('csrf_token')
64 65 66 67
    );
  }

  /**
68
   * Constructs a new CommentViewBuilder.
69 70 71
   *
   * @param string $entity_type
   *   The entity type.
72
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
73 74 75 76 77
   *   The entity manager service.
   * @param \Drupal\field\FieldInfo $field_info
   *   The field info service.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler service.
78 79
   * @param \Drupal\Core\Access\CsrfTokenGenerator $csrf_token
   *   The CSRF token manager service.
80
   */
81 82 83
  public function __construct($entity_type, EntityManagerInterface $entity_manager, FieldInfo $field_info, ModuleHandlerInterface $module_handler, CsrfTokenGenerator $csrf_token) {
    parent::__construct($entity_type);
    $this->entityManager = $entity_manager;
84 85
    $this->fieldInfo = $field_info;
    $this->moduleHandler = $module_handler;
86
    $this->csrfToken = $csrf_token;
87
  }
88 89

  /**
90
   * Overrides Drupal\Core\Entity\EntityViewBuilder::buildContent().
91 92
   *
   * In addition to modifying the content key on entities, this implementation
93 94 95 96
   * will also set the comment entity key which all comments carry.
   *
   * @throws \InvalidArgumentException
   *   Thrown when a comment is attached to an entity that no longer exists.
97
   */
98
  public function buildContent(array $entities, array $displays, $view_mode, $langcode = NULL) {
99 100 101 102 103
    $return = array();
    if (empty($entities)) {
      return $return;
    }

104 105 106
    // Pre-load associated users into cache to leverage multiple loading.
    $uids = array();
    foreach ($entities as $entity) {
107
      $uids[] = $entity->uid->target_id;
108
    }
109
    $this->entityManager->getStorageController('user')->loadMultiple(array_unique($uids));
110

111
    parent::buildContent($entities, $displays, $view_mode, $langcode);
112

113 114 115
    // Load all the entities that have comments attached.
    $commented_entity_ids = array();
    $commented_entities = array();
116
    foreach ($entities as $entity) {
117 118 119 120 121 122
      $commented_entity_ids[$entity->entity_type->value][] = $entity->entity_id->value;
    }
    // Load entities in bulk. This is more performant than using
    // $comment->entity_id->value as we can load them in bulk per type.
    foreach ($commented_entity_ids as $entity_type => $entity_ids) {
      $commented_entities[$entity_type] = $this->entityManager->getStorageController($entity_type)->loadMultiple($entity_ids);
123
    }
124

125
    foreach ($entities as $entity) {
126 127
      if (isset($commented_entities[$entity->entity_type->value][$entity->entity_id->value])) {
        $commented_entity = $commented_entities[$entity->entity_type->value][$entity->entity_id->value];
128 129
      }
      else {
130
        throw new \InvalidArgumentException(t('Invalid entity for comment.'));
131
      }
132 133
      $entity->content['#entity'] = $entity;
      $entity->content['#theme'] = 'comment__' . $entity->field_id->value . '__' . $commented_entity->bundle();
134 135 136 137 138 139
      $entity->content['links'] = array(
        '#theme' => 'links__comment',
        '#pre_render' => array('drupal_pre_render_links'),
        '#attributes' => array('class' => array('links', 'inline')),
      );
      if (empty($entity->in_preview)) {
140
        $entity->content['links'][$this->entityType] = $this->buildLinks($entity, $commented_entity);
141
      }
142 143 144 145 146

      if (!isset($entity->content['#attached'])) {
        $entity->content['#attached'] = array();
      }
      $entity->content['#attached']['library'][] = array('comment', 'drupal.comment-by-viewer');
147
      if ($this->moduleHandler->moduleExists('history') &&  \Drupal::currentUser()->isAuthenticated()) {
148 149
        $entity->content['#attached']['library'][] = array('comment', 'drupal.comment-new-indicator');
      }
150 151 152
    }
  }

153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
  /**
   * Build the default links (reply, edit, delete …) for a comment.
   *
   * @param \Drupal\comment\Entity\CommentInterface $entity
   *   The comment object.
   * @param \Drupal\Core\Entity\EntityInterface $commented_entity
   *   The entity to which the comment is attached.
   *
   * @return array
   *   An array that can be processed by drupal_pre_render_links().
   */
  protected function buildLinks(CommentInterface $entity, EntityInterface $commented_entity) {
    $links = array();
    $status = $commented_entity->get($entity->field_name->value)->status;

    if ($status == COMMENT_OPEN) {
      if ($entity->access('delete')) {
        $links['comment-delete'] = array(
          'title' => t('delete'),
          'href' => "comment/{$entity->id()}/delete",
          'html' => TRUE,
        );
      }

      if ($entity->access('update')) {
        $links['comment-edit'] = array(
          'title' => t('edit'),
          'href' => "comment/{$entity->id()}/edit",
          'html' => TRUE,
        );
      }
      if ($entity->access('create')) {
        $links['comment-reply'] = array(
          'title' => t('reply'),
          'href' => "comment/reply/{$entity->entity_type->value}/{$entity->entity_id->value}/{$entity->field_name->value}/{$entity->id()}",
          'html' => TRUE,
        );
      }
      if ($entity->status->value == COMMENT_NOT_PUBLISHED && $entity->access('approve')) {
        $links['comment-approve'] = array(
          'title' => t('approve'),
          'href' => "comment/{$entity->id()}/approve",
          'html' => TRUE,
          'query' => array('token' => $this->csrfToken->get("comment/{$entity->id()}/approve")),
        );
      }
      if (empty($links)) {
        $comment_post_forbidden = array(
          '#theme' => 'comment_post_forbidden',
          '#commented_entity' => $commented_entity,
          '#field_name' => $entity->field_name->value,
        );
        $links['comment-forbidden']['title'] = drupal_render($comment_post_forbidden);
        $links['comment-forbidden']['html'] = TRUE;
      }
    }

    // Add translations link for translation-enabled comment bundles.
    if ($this->moduleHandler->moduleExists('content_translation') && content_translation_translate_access($entity)) {
      $links['comment-translations'] = array(
        'title' => t('translate'),
        'href' => 'comment/' . $entity->id() . '/translations',
        'html' => TRUE,
      );
    }

    return array(
      '#theme' => 'links__comment__comment',
      // The "entity" property is specified to be present, so no need to
      // check.
      '#links' => $links,
      '#attributes' => array('class' => array('links', 'inline')),
    );
  }

228
  /**
229
   * {@inheritdoc}
230
   */
231 232
  protected function alterBuild(array &$build, EntityInterface $comment, EntityDisplay $display, $view_mode, $langcode = NULL) {
    parent::alterBuild($build, $comment, $display, $view_mode, $langcode);
233 234
    if (empty($comment->in_preview)) {
      $prefix = '';
235 236
      $commented_entity = $this->entityManager->getStorageController($comment->entity_type->value)->load($comment->entity_id->value);
      $instance = $this->fieldInfo->getInstance($commented_entity->entityType(), $commented_entity->bundle(), $comment->field_name->value);
237
      $is_threaded = isset($comment->divs)
238
        && $instance->getFieldSetting('default_mode') == COMMENT_MODE_THREADED;
239 240 241

      // Add indentation div or close open divs as needed.
      if ($is_threaded) {
242
        $build['#attached']['css'][] = drupal_get_path('module', 'comment') . '/css/comment.theme.css';
243 244 245 246
        $prefix .= $comment->divs <= 0 ? str_repeat('</div>', abs($comment->divs)) : "\n" . '<div class="indented">';
      }

      // Add anchor for each comment.
247
      $prefix .= "<a id=\"comment-{$comment->id()}\"></a>\n";
248 249 250 251 252 253 254 255
      $build['#prefix'] = $prefix;

      // Close all open divs.
      if ($is_threaded && !empty($comment->divs_final)) {
        $build['#suffix'] = str_repeat('</div>', $comment->divs_final);
      }
    }
  }
256

257
}