comparison core/modules/comment/src/CommentViewBuilder.php @ 0:c75dbcec494b

Initial commit from drush-created site
author Chris Cannam
date Thu, 05 Jul 2018 14:24:15 +0000
parents
children 12f9dff5fda9
comparison
equal deleted inserted replaced
-1:000000000000 0:c75dbcec494b
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 $attach_history = $this->moduleHandler->moduleExists('history') && $this->currentUser->isAuthenticated();
102
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
109 // depth is higher.
110 $build[$id]['#comment_indent'] = 1;
111 $current_indent++;
112 }
113 else {
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;
118 }
119 }
120
121 // Commented entities already loaded after self::getBuildDefaults().
122 $commented_entity = $entity->getCommentedEntity();
123
124 $build[$id]['#entity'] = $entity;
125 $build[$id]['#theme'] = 'comment__' . $entity->getFieldName() . '__' . $commented_entity->bundle();
126
127 $display = $displays[$entity->bundle()];
128 if ($display->getComponent('links')) {
129 $build[$id]['links'] = [
130 '#lazy_builder' => [
131 'comment.lazy_builders:renderLinks',
132 [
133 $entity->id(),
134 $view_mode,
135 $entity->language()->getId(),
136 !empty($entity->in_preview),
137 ],
138 ],
139 '#create_placeholder' => TRUE,
140 ];
141 }
142
143 if (!isset($build[$id]['#attached'])) {
144 $build[$id]['#attached'] = [];
145 }
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';
149
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,
154 ];
155 }
156 }
157 if ($build[$id]['#comment_threaded']) {
158 // The final comment must close up some hanging divs.
159 $build[$id]['#comment_indent_final'] = $current_indent;
160 }
161 }
162
163 /**
164 * {@inheritdoc}
165 */
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)) {
169 $prefix = '';
170
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">';
174 }
175
176 // Add anchor for each comment.
177 $prefix .= "<a id=\"comment-{$comment->id()}\"></a>\n";
178 $build['#prefix'] = $prefix;
179
180 // Close all open divs.
181 if (!empty($build['#comment_indent_final'])) {
182 $build['#suffix'] = str_repeat('</div>', $build['#comment_indent_final']);
183 }
184 }
185 }
186
187 }