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.
102 foreach ($entities as $id => $entity) {
103 if ($build[$id]['#comment_threaded']) {
104 $comment_indent = count(explode('.', $entity->getThread())) - 1;
105 if ($comment_indent > $current_indent) {
106 // Set 1 to indent this comment from the previous one (its parent).
107 // Set only one extra level of indenting even if the difference in
109 $build[$id]['#comment_indent'] = 1;
113 // Set zero if this comment is on the same level as the previous one
114 // or negative value to point an amount indents to close.
115 $build[$id]['#comment_indent'] = $comment_indent - $current_indent;
116 $current_indent = $comment_indent;
120 // Commented entities already loaded after self::getBuildDefaults().
121 $commented_entity = $entity->getCommentedEntity();
123 $build[$id]['#entity'] = $entity;
124 $build[$id]['#theme'] = 'comment__' . $entity->getFieldName() . '__' . $commented_entity->bundle();
126 $display = $displays[$entity->bundle()];
127 if ($display->getComponent('links')) {
128 $build[$id]['links'] = [
129 '#lazy_builder' => ['comment.lazy_builders:renderLinks', [
132 $entity->language()->getId(),
133 !empty($entity->in_preview),
135 '#create_placeholder' => TRUE,
139 if (!isset($build[$id]['#attached'])) {
140 $build[$id]['#attached'] = [];
142 $build[$id]['#attached']['library'][] = 'comment/drupal.comment-by-viewer';
143 if ($this->moduleHandler->moduleExists('history') && $this->currentUser->isAuthenticated()) {
144 $build[$id]['#attached']['library'][] = 'comment/drupal.comment-new-indicator';
146 // Embed the metadata for the comment "new" indicators on this node.
147 $build[$id]['history'] = [
148 '#lazy_builder' => ['history_attach_timestamp', [$commented_entity->id()]],
149 '#create_placeholder' => TRUE,
153 if ($build[$id]['#comment_threaded']) {
154 // The final comment must close up some hanging divs.
155 $build[$id]['#comment_indent_final'] = $current_indent;
162 protected function alterBuild(array &$build, EntityInterface $comment, EntityViewDisplayInterface $display, $view_mode) {
163 parent::alterBuild($build, $comment, $display, $view_mode);
164 if (empty($comment->in_preview)) {
167 // Add indentation div or close open divs as needed.
168 if ($build['#comment_threaded']) {
169 $prefix .= $build['#comment_indent'] <= 0 ? str_repeat('</div>', abs($build['#comment_indent'])) : "\n" . '<div class="indented">';
172 // Add anchor for each comment.
173 $prefix .= "<a id=\"comment-{$comment->id()}\"></a>\n";
174 $build['#prefix'] = $prefix;
176 // Close all open divs.
177 if (!empty($build['#comment_indent_final'])) {
178 $build['#suffix'] = str_repeat('</div>', $build['#comment_indent_final']);