Upgraded drupal core with security updates
[yaffs-website] / web / core / modules / comment / src / CommentViewBuilder.php
1 <?php
2
3 namespace Drupal\comment;
4
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;
13
14 /**
15  * View builder handler for comments.
16  */
17 class CommentViewBuilder extends EntityViewBuilder {
18
19   /**
20    * The current user.
21    *
22    * @var \Drupal\Core\Session\AccountInterface
23    */
24   protected $currentUser;
25
26   /**
27    * Constructs a new CommentViewBuilder.
28    *
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
36    *   The current user.
37    */
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;
41   }
42
43   /**
44    * {@inheritdoc}
45    */
46   public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
47     return new static(
48       $entity_type,
49       $container->get('entity.manager'),
50       $container->get('language_manager'),
51       $container->get('current_user')
52     );
53   }
54
55   /**
56    * {@inheritdoc}
57    */
58   protected function getBuildDefaults(EntityInterface $entity, $view_mode) {
59     $build = parent::getBuildDefaults($entity, $view_mode);
60
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']);
70     }
71
72     return $build;
73   }
74
75   /**
76    * {@inheritdoc}
77    *
78    * In addition to modifying the content key on entities, this implementation
79    * will also set the comment entity key which all comments carry.
80    *
81    * @throws \InvalidArgumentException
82    *   Thrown when a comment is attached to an entity that no longer exists.
83    */
84   public function buildComponents(array &$build, array $entities, array $displays, $view_mode) {
85     /** @var \Drupal\comment\CommentInterface[] $entities */
86     if (empty($entities)) {
87       return;
88     }
89
90     // Pre-load associated users into cache to leverage multiple loading.
91     $uids = [];
92     foreach ($entities as $entity) {
93       $uids[] = $entity->getOwnerId();
94     }
95     $this->entityManager->getStorage('user')->loadMultiple(array_unique($uids));
96
97     parent::buildComponents($build, $entities, $displays, $view_mode);
98
99     // A counter to track the indentation level.
100     $current_indent = 0;
101
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
108           // depth is higher.
109           $build[$id]['#comment_indent'] = 1;
110           $current_indent++;
111         }
112         else {
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;
117         }
118       }
119
120       // Commented entities already loaded after self::getBuildDefaults().
121       $commented_entity = $entity->getCommentedEntity();
122
123       $build[$id]['#entity'] = $entity;
124       $build[$id]['#theme'] = 'comment__' . $entity->getFieldName() . '__' . $commented_entity->bundle();
125
126       $display = $displays[$entity->bundle()];
127       if ($display->getComponent('links')) {
128         $build[$id]['links'] = [
129           '#lazy_builder' => ['comment.lazy_builders:renderLinks', [
130             $entity->id(),
131             $view_mode,
132             $entity->language()->getId(),
133             !empty($entity->in_preview),
134           ]],
135           '#create_placeholder' => TRUE,
136         ];
137       }
138
139       if (!isset($build[$id]['#attached'])) {
140         $build[$id]['#attached'] = [];
141       }
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';
145
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,
150         ];
151       }
152     }
153     if ($build[$id]['#comment_threaded']) {
154       // The final comment must close up some hanging divs.
155       $build[$id]['#comment_indent_final'] = $current_indent;
156     }
157   }
158
159   /**
160    * {@inheritdoc}
161    */
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)) {
165       $prefix = '';
166
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">';
170       }
171
172       // Add anchor for each comment.
173       $prefix .= "<a id=\"comment-{$comment->id()}\"></a>\n";
174       $build['#prefix'] = $prefix;
175
176       // Close all open divs.
177       if (!empty($build['#comment_indent_final'])) {
178         $build['#suffix'] = str_repeat('</div>', $build['#comment_indent_final']);
179       }
180     }
181   }
182
183 }