CommentViewBuilder.php 10.8 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\Display\EntityViewDisplayInterface;
13
use Drupal\Core\Entity\EntityInterface;
14
use Drupal\Core\Entity\EntityManagerInterface;
15
use Drupal\Core\Entity\EntityViewBuilderInterface;
16
use Drupal\Core\Extension\ModuleHandlerInterface;
17
use Drupal\Core\Entity\EntityViewBuilder;
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 33 34 35 36 37 38 39

  /**
   * The field info service.
   *
   * @var \Drupal\field\FieldInfo
   */
  protected $fieldInfo;

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

40 41 42 43 44 45 46
  /**
   * The CSRF token manager service.
   *
   * @var \Drupal\Core\Access\CsrfTokenGenerator
   */
  protected $csrfToken;

47 48 49 50 51 52
  /**
   * {@inheritdoc}
   */
  public static function createInstance(ContainerInterface $container, $entity_type, array $entity_info) {
    return new static(
      $entity_type,
53
      $entity_info,
54 55
      $container->get('entity.manager'),
      $container->get('field.info'),
56 57
      $container->get('module_handler'),
      $container->get('csrf_token')
58 59 60 61
    );
  }

  /**
62
   * Constructs a new CommentViewBuilder.
63 64 65
   *
   * @param string $entity_type
   *   The entity type.
66 67
   * @param array $entity_info
   *   The entity information array.
68
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
69 70 71 72 73
   *   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.
74 75
   * @param \Drupal\Core\Access\CsrfTokenGenerator $csrf_token
   *   The CSRF token manager service.
76
   */
77 78
  public function __construct($entity_type, array $entity_info, EntityManagerInterface $entity_manager, FieldInfo $field_info, ModuleHandlerInterface $module_handler, CsrfTokenGenerator $csrf_token) {
    parent::__construct($entity_type, $entity_info, $entity_manager);
79 80
    $this->fieldInfo = $field_info;
    $this->moduleHandler = $module_handler;
81
    $this->csrfToken = $csrf_token;
82
  }
83 84

  /**
85
   * Overrides Drupal\Core\Entity\EntityViewBuilder::buildContent().
86 87
   *
   * In addition to modifying the content key on entities, this implementation
88 89 90 91
   * 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.
92
   */
93
  public function buildContent(array $entities, array $displays, $view_mode, $langcode = NULL) {
94 95 96 97 98
    $return = array();
    if (empty($entities)) {
      return $return;
    }

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

106
    parent::buildContent($entities, $displays, $view_mode, $langcode);
107

108 109 110
    // Load all the entities that have comments attached.
    $commented_entity_ids = array();
    $commented_entities = array();
111
    foreach ($entities as $entity) {
112 113 114 115 116 117
      $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);
118
    }
119

120
    foreach ($entities as $entity) {
121 122
      if (isset($commented_entities[$entity->entity_type->value][$entity->entity_id->value])) {
        $commented_entity = $commented_entities[$entity->entity_type->value][$entity->entity_id->value];
123 124
      }
      else {
125
        throw new \InvalidArgumentException(t('Invalid entity for comment.'));
126
      }
127 128
      $entity->content['#entity'] = $entity;
      $entity->content['#theme'] = 'comment__' . $entity->field_id->value . '__' . $commented_entity->bundle();
129
      $entity->content['links'] = array(
130 131 132 133 134 135 136 137 138 139
        '#type' => 'render_cache_placeholder',
        '#callback' => '\Drupal\comment\CommentViewBuilder::renderLinks',
        '#context' => array(
          'comment_entity_id' => $entity->id(),
          'view_mode' => $view_mode,
          'langcode' => $langcode,
          'commented_entity_type' => $commented_entity->entityType(),
          'commented_entity_id' => $commented_entity->id(),
          'in_preview' => !empty($entity->in_preview),
        ),
140
      );
141 142 143 144 145

      if (!isset($entity->content['#attached'])) {
        $entity->content['#attached'] = array();
      }
      $entity->content['#attached']['library'][] = array('comment', 'drupal.comment-by-viewer');
146
      if ($this->moduleHandler->moduleExists('history') &&  \Drupal::currentUser()->isAuthenticated()) {
147 148
        $entity->content['#attached']['library'][] = array('comment', 'drupal.comment-new-indicator');
      }
149 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
  /**
   * #post_render_cache callback; replaces the placeholder with comment links.
   *
   * Renders the links on a comment.
   *
   * @param array $context
   *   An array with the following keys:
   *   - comment_entity_id: a comment entity ID
   *   - view_mode: the view mode in which the comment entity is being viewed
   *   - langcode: in which language the comment entity is being viewed
   *   - commented_entity_type: the entity type to which the comment is attached
   *   - commented_entity_id: the entity ID to which the comment is attached
   *   - in_preview: whether the comment is currently being previewed
   *
   * @return array
   *   A renderable array representing the comment links.
   */
  public static function renderLinks(array $context) {
    $links = array(
      '#theme' => 'links__comment',
      '#pre_render' => array('drupal_pre_render_links'),
      '#attributes' => array('class' => array('links', 'inline')),
    );

    if (!$context['in_preview']) {
      $entity = entity_load('comment', $context['comment_entity_id']);
      $commented_entity = entity_load($context['commented_entity_type'], $context['commented_entity_id']);

      $links['comment'] = self::buildLinks($entity, $commented_entity);

      // Allow other modules to alter the comment links.
      $hook_context = array(
        'view_mode' => $context['view_mode'],
        'langcode' => $context['langcode'],
        'commented_entity' => $commented_entity
      );
      \Drupal::moduleHandler()->alter('comment_links', $links, $entity, $hook_context);
    }

    return $links;
  }

194 195 196
  /**
   * Build the default links (reply, edit, delete …) for a comment.
   *
197
   * @param \Drupal\comment\CommentInterface $entity
198 199 200 201 202 203 204
   *   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().
   */
205
  protected static function buildLinks(CommentInterface $entity, EntityInterface $commented_entity) {
206 207 208
    $links = array();
    $status = $commented_entity->get($entity->field_name->value)->status;

209 210
    $container = \Drupal::getContainer();

211 212 213
    if ($status == COMMENT_OPEN) {
      if ($entity->access('delete')) {
        $links['comment-delete'] = array(
214
          'title' => t('Delete'),
215 216 217 218 219 220 221
          'href' => "comment/{$entity->id()}/delete",
          'html' => TRUE,
        );
      }

      if ($entity->access('update')) {
        $links['comment-edit'] = array(
222
          'title' => t('Edit'),
223 224 225 226 227 228
          'href' => "comment/{$entity->id()}/edit",
          'html' => TRUE,
        );
      }
      if ($entity->access('create')) {
        $links['comment-reply'] = array(
229
          'title' => t('Reply'),
230 231 232 233 234 235
          '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(
236
          'title' => t('Approve'),
237 238
          'route_name' => 'comment.approve',
          'route_parameters' => array('comment' => $entity->id()),
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
          'html' => TRUE,
        );
      }
      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.
254
    if ($container->get('module_handler')->moduleExists('content_translation') && content_translation_translate_access($entity)) {
255
      $links['comment-translations'] = array(
256
        'title' => t('Translate'),
257 258 259 260 261 262 263 264 265 266 267 268 269 270
        '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')),
    );
  }

271
  /**
272
   * {@inheritdoc}
273
   */
274
  protected function alterBuild(array &$build, EntityInterface $comment, EntityViewDisplayInterface $display, $view_mode, $langcode = NULL) {
275
    parent::alterBuild($build, $comment, $display, $view_mode, $langcode);
276 277
    if (empty($comment->in_preview)) {
      $prefix = '';
278 279
      $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);
280
      $is_threaded = isset($comment->divs)
281
        && $instance->getSetting('default_mode') == COMMENT_MODE_THREADED;
282 283 284

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

      // Add anchor for each comment.
290
      $prefix .= "<a id=\"comment-{$comment->id()}\"></a>\n";
291 292 293 294 295 296 297 298
      $build['#prefix'] = $prefix;

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

300
}