CommentViewBuilder.php 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. <?php
  2. namespace Drupal\comment;
  3. use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
  4. use Drupal\Core\Entity\EntityInterface;
  5. use Drupal\Core\Entity\EntityManagerInterface;
  6. use Drupal\Core\Entity\EntityTypeInterface;
  7. use Drupal\Core\Entity\EntityViewBuilder;
  8. use Drupal\Core\Language\LanguageManagerInterface;
  9. use Drupal\Core\Session\AccountInterface;
  10. use Symfony\Component\DependencyInjection\ContainerInterface;
  11. /**
  12. * View builder handler for comments.
  13. */
  14. class CommentViewBuilder extends EntityViewBuilder {
  15. /**
  16. * The current user.
  17. *
  18. * @var \Drupal\Core\Session\AccountInterface
  19. */
  20. protected $currentUser;
  21. /**
  22. * Constructs a new CommentViewBuilder.
  23. *
  24. * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
  25. * The entity type definition.
  26. * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
  27. * The entity manager service.
  28. * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
  29. * The language manager.
  30. * @param \Drupal\Core\Session\AccountInterface $current_user
  31. * The current user.
  32. */
  33. public function __construct(EntityTypeInterface $entity_type, EntityManagerInterface $entity_manager, LanguageManagerInterface $language_manager, AccountInterface $current_user) {
  34. parent::__construct($entity_type, $entity_manager, $language_manager);
  35. $this->currentUser = $current_user;
  36. }
  37. /**
  38. * {@inheritdoc}
  39. */
  40. public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
  41. return new static(
  42. $entity_type,
  43. $container->get('entity.manager'),
  44. $container->get('language_manager'),
  45. $container->get('current_user')
  46. );
  47. }
  48. /**
  49. * {@inheritdoc}
  50. */
  51. protected function getBuildDefaults(EntityInterface $entity, $view_mode) {
  52. $build = parent::getBuildDefaults($entity, $view_mode);
  53. /** @var \Drupal\comment\CommentInterface $entity */
  54. // Store a threading field setting to use later in self::buildComponents().
  55. $build['#comment_threaded'] = $entity->getCommentedEntity()
  56. ->getFieldDefinition($entity->getFieldName())
  57. ->getSetting('default_mode') === CommentManagerInterface::COMMENT_MODE_THREADED;
  58. // If threading is enabled, don't render cache individual comments, but do
  59. // keep the cacheability metadata, so it can bubble up.
  60. if ($build['#comment_threaded']) {
  61. unset($build['#cache']['keys']);
  62. }
  63. return $build;
  64. }
  65. /**
  66. * {@inheritdoc}
  67. *
  68. * In addition to modifying the content key on entities, this implementation
  69. * will also set the comment entity key which all comments carry.
  70. *
  71. * @throws \InvalidArgumentException
  72. * Thrown when a comment is attached to an entity that no longer exists.
  73. */
  74. public function buildComponents(array &$build, array $entities, array $displays, $view_mode) {
  75. /** @var \Drupal\comment\CommentInterface[] $entities */
  76. if (empty($entities)) {
  77. return;
  78. }
  79. // Pre-load associated users into cache to leverage multiple loading.
  80. $uids = [];
  81. foreach ($entities as $entity) {
  82. $uids[] = $entity->getOwnerId();
  83. }
  84. $this->entityManager->getStorage('user')->loadMultiple(array_unique($uids));
  85. parent::buildComponents($build, $entities, $displays, $view_mode);
  86. // A counter to track the indentation level.
  87. $current_indent = 0;
  88. foreach ($entities as $id => $entity) {
  89. if ($build[$id]['#comment_threaded']) {
  90. $comment_indent = count(explode('.', $entity->getThread())) - 1;
  91. if ($comment_indent > $current_indent) {
  92. // Set 1 to indent this comment from the previous one (its parent).
  93. // Set only one extra level of indenting even if the difference in
  94. // depth is higher.
  95. $build[$id]['#comment_indent'] = 1;
  96. $current_indent++;
  97. }
  98. else {
  99. // Set zero if this comment is on the same level as the previous one
  100. // or negative value to point an amount indents to close.
  101. $build[$id]['#comment_indent'] = $comment_indent - $current_indent;
  102. $current_indent = $comment_indent;
  103. }
  104. }
  105. // Commented entities already loaded after self::getBuildDefaults().
  106. $commented_entity = $entity->getCommentedEntity();
  107. $build[$id]['#entity'] = $entity;
  108. $build[$id]['#theme'] = 'comment__' . $entity->getFieldName() . '__' . $commented_entity->bundle();
  109. $display = $displays[$entity->bundle()];
  110. if ($display->getComponent('links')) {
  111. $build[$id]['links'] = [
  112. '#lazy_builder' => [
  113. 'comment.lazy_builders:renderLinks',
  114. [
  115. $entity->id(),
  116. $view_mode,
  117. $entity->language()->getId(),
  118. !empty($entity->in_preview),
  119. ],
  120. ],
  121. '#create_placeholder' => TRUE,
  122. ];
  123. }
  124. if (!isset($build[$id]['#attached'])) {
  125. $build[$id]['#attached'] = [];
  126. }
  127. $build[$id]['#attached']['library'][] = 'comment/drupal.comment-by-viewer';
  128. if ($this->moduleHandler->moduleExists('history') && $this->currentUser->isAuthenticated()) {
  129. $build[$id]['#attached']['library'][] = 'comment/drupal.comment-new-indicator';
  130. // Embed the metadata for the comment "new" indicators on this node.
  131. $build[$id]['history'] = [
  132. '#lazy_builder' => ['history_attach_timestamp', [$commented_entity->id()]],
  133. '#create_placeholder' => TRUE,
  134. ];
  135. }
  136. }
  137. if ($build[$id]['#comment_threaded']) {
  138. // The final comment must close up some hanging divs.
  139. $build[$id]['#comment_indent_final'] = $current_indent;
  140. }
  141. }
  142. /**
  143. * {@inheritdoc}
  144. */
  145. protected function alterBuild(array &$build, EntityInterface $comment, EntityViewDisplayInterface $display, $view_mode) {
  146. parent::alterBuild($build, $comment, $display, $view_mode);
  147. if (empty($comment->in_preview)) {
  148. $prefix = '';
  149. // Add indentation div or close open divs as needed.
  150. if ($build['#comment_threaded']) {
  151. $prefix .= $build['#comment_indent'] <= 0 ? str_repeat('</div>', abs($build['#comment_indent'])) : "\n" . '<div class="indented">';
  152. }
  153. // Add anchor for each comment.
  154. $prefix .= "<a id=\"comment-{$comment->id()}\"></a>\n";
  155. $build['#prefix'] = $prefix;
  156. // Close all open divs.
  157. if (!empty($build['#comment_indent_final'])) {
  158. $build['#suffix'] = str_repeat('</div>', $build['#comment_indent_final']);
  159. }
  160. }
  161. }
  162. }