3 namespace Drupal\comment;
5 use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
6 use Drupal\Core\Entity\EntityInterface;
7 use Drupal\Core\Entity\EntityManagerInterface;
8 use Drupal\Core\Entity\EntityTypeInterface;
9 use Drupal\Core\Entity\EntityViewBuilder;
10 use Drupal\Core\Language\LanguageManagerInterface;
11 use Drupal\Core\Session\AccountInterface;
12 use Symfony\Component\DependencyInjection\ContainerInterface;
15 * View builder handler for comments.
17 class CommentViewBuilder extends EntityViewBuilder {
22 * @var \Drupal\Core\Session\AccountInterface
24 protected $currentUser;
27 * Constructs a new CommentViewBuilder.
29 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
30 * The entity type definition.
31 * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
32 * The entity manager service.
33 * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
34 * The language manager.
35 * @param \Drupal\Core\Session\AccountInterface $current_user
38 public function __construct(EntityTypeInterface $entity_type, EntityManagerInterface $entity_manager, LanguageManagerInterface $language_manager, AccountInterface $current_user) {
39 parent::__construct($entity_type, $entity_manager, $language_manager);
40 $this->currentUser = $current_user;
46 public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
49 $container->get('entity.manager'),
50 $container->get('language_manager'),
51 $container->get('current_user')
58 protected function getBuildDefaults(EntityInterface $entity, $view_mode) {
59 $build = parent::getBuildDefaults($entity, $view_mode);
61 /** @var \Drupal\comment\CommentInterface $entity */
62 // Store a threading field setting to use later in self::buildComponents().
63 $build['#comment_threaded'] = $entity->getCommentedEntity()
64 ->getFieldDefinition($entity->getFieldName())
65 ->getSetting('default_mode') === CommentManagerInterface::COMMENT_MODE_THREADED;
66 // If threading is enabled, don't render cache individual comments, but do
67 // keep the cacheability metadata, so it can bubble up.
68 if ($build['#comment_threaded']) {
69 unset($build['#cache']['keys']);
78 * In addition to modifying the content key on entities, this implementation
79 * will also set the comment entity key which all comments carry.
81 * @throws \InvalidArgumentException
82 * Thrown when a comment is attached to an entity that no longer exists.
84 public function buildComponents(array &$build, array $entities, array $displays, $view_mode) {
85 /** @var \Drupal\comment\CommentInterface[] $entities */
86 if (empty($entities)) {
90 // Pre-load associated users into cache to leverage multiple loading.
92 foreach ($entities as $entity) {
93 $uids[] = $entity->getOwnerId();
95 $this->entityManager->getStorage('user')->loadMultiple(array_unique($uids));
97 parent::buildComponents($build, $entities, $displays, $view_mode);
99 // A counter to track the indentation level.
101 $attach_history = $this->moduleHandler->moduleExists('history') && $this->currentUser->isAuthenticated();
103 foreach ($entities as $id => $entity) {
104 if ($build[$id]['#comment_threaded']) {
105 $comment_indent = count(explode('.', $entity->getThread())) - 1;
106 if ($comment_indent > $current_indent) {
107 // Set 1 to indent this comment from the previous one (its parent).
108 // Set only one extra level of indenting even if the difference in
110 $build[$id]['#comment_indent'] = 1;
114 // Set zero if this comment is on the same level as the previous one
115 // or negative value to point an amount indents to close.
116 $build[$id]['#comment_indent'] = $comment_indent - $current_indent;
117 $current_indent = $comment_indent;
121 // Commented entities already loaded after self::getBuildDefaults().
122 $commented_entity = $entity->getCommentedEntity();
124 $build[$id]['#entity'] = $entity;
125 $build[$id]['#theme'] = 'comment__' . $entity->getFieldName() . '__' . $commented_entity->bundle();
127 $display = $displays[$entity->bundle()];
128 if ($display->getComponent('links')) {
129 $build[$id]['links'] = [
131 'comment.lazy_builders:renderLinks',
135 $entity->language()->getId(),
136 !empty($entity->in_preview),
139 '#create_placeholder' => TRUE,
143 if (!isset($build[$id]['#attached'])) {
144 $build[$id]['#attached'] = [];
146 $build[$id]['#attached']['library'][] = 'comment/drupal.comment-by-viewer';
147 if ($attach_history && $commented_entity->getEntityTypeId() === 'node') {
148 $build[$id]['#attached']['library'][] = 'comment/drupal.comment-new-indicator';
150 // Embed the metadata for the comment "new" indicators on this node.
151 $build[$id]['history'] = [
152 '#lazy_builder' => ['history_attach_timestamp', [$commented_entity->id()]],
153 '#create_placeholder' => TRUE,
157 if ($build[$id]['#comment_threaded']) {
158 // The final comment must close up some hanging divs.
159 $build[$id]['#comment_indent_final'] = $current_indent;
166 protected function alterBuild(array &$build, EntityInterface $comment, EntityViewDisplayInterface $display, $view_mode) {
167 parent::alterBuild($build, $comment, $display, $view_mode);
168 if (empty($comment->in_preview)) {
171 // Add indentation div or close open divs as needed.
172 if ($build['#comment_threaded']) {
173 $prefix .= $build['#comment_indent'] <= 0 ? str_repeat('</div>', abs($build['#comment_indent'])) : "\n" . '<div class="indented">';
176 // Add anchor for each comment.
177 $prefix .= "<a id=\"comment-{$comment->id()}\"></a>\n";
178 $build['#prefix'] = $prefix;
180 // Close all open divs.
181 if (!empty($build['#comment_indent_final'])) {
182 $build['#suffix'] = str_repeat('</div>', $build['#comment_indent_final']);