PageRenderTime 52ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/core/modules/comment/src/Plugin/Field/FieldFormatter/CommentDefaultFormatter.php

http://github.com/drupal/drupal
PHP | 301 lines | 177 code | 23 blank | 101 comment | 17 complexity | 45e9f1e8ead73630f16394170116eb3f MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1
  1. <?php
  2. namespace Drupal\comment\Plugin\Field\FieldFormatter;
  3. use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
  4. use Drupal\Core\DependencyInjection\DeprecatedServicePropertyTrait;
  5. use Drupal\Core\Entity\Entity\EntityViewDisplay;
  6. use Drupal\Core\Entity\EntityDisplayRepositoryInterface;
  7. use Drupal\Core\Entity\EntityFormBuilderInterface;
  8. use Drupal\Core\Entity\EntityTypeManagerInterface;
  9. use Drupal\Core\Field\FieldItemListInterface;
  10. use Drupal\Core\Form\FormStateInterface;
  11. use Drupal\Core\Session\AccountInterface;
  12. use Drupal\Core\Field\FieldDefinitionInterface;
  13. use Drupal\Core\Field\FormatterBase;
  14. use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
  15. use Drupal\Core\Routing\RouteMatchInterface;
  16. use Symfony\Component\DependencyInjection\ContainerInterface;
  17. /**
  18. * Provides a default comment formatter.
  19. *
  20. * @FieldFormatter(
  21. * id = "comment_default",
  22. * module = "comment",
  23. * label = @Translation("Comment list"),
  24. * field_types = {
  25. * "comment"
  26. * },
  27. * quickedit = {
  28. * "editor" = "disabled"
  29. * }
  30. * )
  31. */
  32. class CommentDefaultFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
  33. use DeprecatedServicePropertyTrait;
  34. /**
  35. * {@inheritdoc}
  36. */
  37. protected $deprecatedProperties = ['entityManager' => 'entity.manager'];
  38. /**
  39. * {@inheritdoc}
  40. */
  41. public static function defaultSettings() {
  42. return [
  43. 'view_mode' => 'default',
  44. 'pager_id' => 0,
  45. ] + parent::defaultSettings();
  46. }
  47. /**
  48. * The comment storage.
  49. *
  50. * @var \Drupal\comment\CommentStorageInterface
  51. */
  52. protected $storage;
  53. /**
  54. * The current user.
  55. *
  56. * @var \Drupal\Core\Session\AccountInterface
  57. */
  58. protected $currentUser;
  59. /**
  60. * The comment render controller.
  61. *
  62. * @var \Drupal\Core\Entity\EntityViewBuilderInterface
  63. */
  64. protected $viewBuilder;
  65. /**
  66. * The entity display repository.
  67. *
  68. * @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface
  69. */
  70. protected $entityDisplayRepository;
  71. /**
  72. * The entity form builder.
  73. *
  74. * @var \Drupal\Core\Entity\EntityFormBuilderInterface
  75. */
  76. protected $entityFormBuilder;
  77. /**
  78. * @var \Drupal\Core\Routing\RouteMatchInterface
  79. */
  80. protected $routeMatch;
  81. /**
  82. * {@inheritdoc}
  83. */
  84. public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
  85. return new static(
  86. $plugin_id,
  87. $plugin_definition,
  88. $configuration['field_definition'],
  89. $configuration['settings'],
  90. $configuration['label'],
  91. $configuration['view_mode'],
  92. $configuration['third_party_settings'],
  93. $container->get('current_user'),
  94. $container->get('entity_type.manager'),
  95. $container->get('entity.form_builder'),
  96. $container->get('current_route_match'),
  97. $container->get('entity_display.repository')
  98. );
  99. }
  100. /**
  101. * Constructs a new CommentDefaultFormatter.
  102. *
  103. * @param string $plugin_id
  104. * The plugin_id for the formatter.
  105. * @param mixed $plugin_definition
  106. * The plugin implementation definition.
  107. * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
  108. * The definition of the field to which the formatter is associated.
  109. * @param array $settings
  110. * The formatter settings.
  111. * @param string $label
  112. * The formatter label display setting.
  113. * @param string $view_mode
  114. * The view mode.
  115. * @param array $third_party_settings
  116. * Third party settings.
  117. * @param \Drupal\Core\Session\AccountInterface $current_user
  118. * The current user.
  119. * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
  120. * The entity type manager.
  121. * @param \Drupal\Core\Entity\EntityFormBuilderInterface $entity_form_builder
  122. * The entity form builder.
  123. * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
  124. * The route match object.
  125. * @param \Drupal\Core\Entity\EntityDisplayRepositoryInterface $entity_display_repository
  126. * The entity display repository.
  127. */
  128. public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, AccountInterface $current_user, EntityTypeManagerInterface $entity_type_manager, EntityFormBuilderInterface $entity_form_builder, RouteMatchInterface $route_match, EntityDisplayRepositoryInterface $entity_display_repository = NULL) {
  129. parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
  130. $this->viewBuilder = $entity_type_manager->getViewBuilder('comment');
  131. $this->storage = $entity_type_manager->getStorage('comment');
  132. $this->currentUser = $current_user;
  133. $this->entityFormBuilder = $entity_form_builder;
  134. $this->routeMatch = $route_match;
  135. if (!$entity_display_repository) {
  136. @trigger_error('Calling RssPluginBase::__construct() with the $entity_repository argument is supported in drupal:8.7.0 and will be required before drupal:9.0.0. See https://www.drupal.org/node/2549139.', E_USER_DEPRECATED);
  137. $entity_display_repository = \Drupal::service('entity_display.repository');
  138. }
  139. $this->entityDisplayRepository = $entity_display_repository;
  140. }
  141. /**
  142. * {@inheritdoc}
  143. */
  144. public function viewElements(FieldItemListInterface $items, $langcode) {
  145. $elements = [];
  146. $output = [];
  147. $field_name = $this->fieldDefinition->getName();
  148. $entity = $items->getEntity();
  149. $status = $items->status;
  150. if ($status != CommentItemInterface::HIDDEN && empty($entity->in_preview) &&
  151. // Comments are added to the search results and search index by
  152. // comment_node_update_index() instead of by this formatter, so don't
  153. // return anything if the view mode is search_index or search_result.
  154. !in_array($this->viewMode, ['search_result', 'search_index'])) {
  155. $comment_settings = $this->getFieldSettings();
  156. // Only attempt to render comments if the entity has visible comments.
  157. // Unpublished comments are not included in
  158. // $entity->get($field_name)->comment_count, but unpublished comments
  159. // should display if the user is an administrator.
  160. $elements['#cache']['contexts'][] = 'user.permissions';
  161. if ($this->currentUser->hasPermission('access comments') || $this->currentUser->hasPermission('administer comments')) {
  162. $output['comments'] = [];
  163. if ($entity->get($field_name)->comment_count || $this->currentUser->hasPermission('administer comments')) {
  164. $mode = $comment_settings['default_mode'];
  165. $comments_per_page = $comment_settings['per_page'];
  166. $comments = $this->storage->loadThread($entity, $field_name, $mode, $comments_per_page, $this->getSetting('pager_id'));
  167. if ($comments) {
  168. $build = $this->viewBuilder->viewMultiple($comments, $this->getSetting('view_mode'));
  169. $build['pager']['#type'] = 'pager';
  170. // CommentController::commentPermalink() calculates the page number
  171. // where a specific comment appears and does a subrequest pointing to
  172. // that page, we need to pass that subrequest route to our pager to
  173. // keep the pager working.
  174. $build['pager']['#route_name'] = $this->routeMatch->getRouteObject();
  175. $build['pager']['#route_parameters'] = $this->routeMatch->getRawParameters()->all();
  176. if ($this->getSetting('pager_id')) {
  177. $build['pager']['#element'] = $this->getSetting('pager_id');
  178. }
  179. $output['comments'] += $build;
  180. }
  181. }
  182. }
  183. // Append comment form if the comments are open and the form is set to
  184. // display below the entity. Do not show the form for the print view mode.
  185. if ($status == CommentItemInterface::OPEN && $comment_settings['form_location'] == CommentItemInterface::FORM_BELOW && $this->viewMode != 'print') {
  186. // Only show the add comment form if the user has permission.
  187. $elements['#cache']['contexts'][] = 'user.roles';
  188. if ($this->currentUser->hasPermission('post comments')) {
  189. $output['comment_form'] = [
  190. '#lazy_builder' => [
  191. 'comment.lazy_builders:renderForm',
  192. [
  193. $entity->getEntityTypeId(),
  194. $entity->id(),
  195. $field_name,
  196. $this->getFieldSetting('comment_type'),
  197. ],
  198. ],
  199. '#create_placeholder' => TRUE,
  200. ];
  201. }
  202. }
  203. $elements[] = $output + [
  204. '#comment_type' => $this->getFieldSetting('comment_type'),
  205. '#comment_display_mode' => $this->getFieldSetting('default_mode'),
  206. 'comments' => [],
  207. 'comment_form' => [],
  208. ];
  209. }
  210. return $elements;
  211. }
  212. /**
  213. * {@inheritdoc}
  214. */
  215. public function settingsForm(array $form, FormStateInterface $form_state) {
  216. $element = [];
  217. $view_modes = $this->getViewModes();
  218. $element['view_mode'] = [
  219. '#type' => 'select',
  220. '#title' => $this->t('Comments view mode'),
  221. '#description' => $this->t('Select the view mode used to show the list of comments.'),
  222. '#default_value' => $this->getSetting('view_mode'),
  223. '#options' => $view_modes,
  224. // Only show the select element when there are more than one options.
  225. '#access' => count($view_modes) > 1,
  226. ];
  227. $element['pager_id'] = [
  228. '#type' => 'select',
  229. '#title' => $this->t('Pager ID'),
  230. '#options' => range(0, 10),
  231. '#default_value' => $this->getSetting('pager_id'),
  232. '#description' => $this->t("Unless you're experiencing problems with pagers related to this field, you should leave this at 0. If using multiple pagers on one page you may need to set this number to a higher value so as not to conflict within the ?page= array. Large values will add a lot of commas to your URLs, so avoid if possible."),
  233. ];
  234. return $element;
  235. }
  236. /**
  237. * {@inheritdoc}
  238. */
  239. public function settingsSummary() {
  240. $view_mode = $this->getSetting('view_mode');
  241. $view_modes = $this->getViewModes();
  242. $view_mode_label = isset($view_modes[$view_mode]) ? $view_modes[$view_mode] : 'default';
  243. $summary = [$this->t('Comment view mode: @mode', ['@mode' => $view_mode_label])];
  244. if ($pager_id = $this->getSetting('pager_id')) {
  245. $summary[] = $this->t('Pager ID: @id', ['@id' => $pager_id]);
  246. }
  247. return $summary;
  248. }
  249. /**
  250. * {@inheritdoc}
  251. */
  252. public function calculateDependencies() {
  253. $dependencies = parent::calculateDependencies();
  254. if ($mode = $this->getSetting('view_mode')) {
  255. if ($bundle = $this->getFieldSetting('comment_type')) {
  256. /** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display */
  257. if ($display = EntityViewDisplay::load("comment.$bundle.$mode")) {
  258. $dependencies[$display->getConfigDependencyKey()][] = $display->getConfigDependencyName();
  259. }
  260. }
  261. }
  262. return $dependencies;
  263. }
  264. /**
  265. * Provides a list of comment view modes for the configured comment type.
  266. *
  267. * @return array
  268. * Associative array keyed by view mode key and having the view mode label
  269. * as value.
  270. */
  271. protected function getViewModes() {
  272. return $this->entityDisplayRepository->getViewModeOptionsByBundle('comment', $this->getFieldSetting('comment_type'));
  273. }
  274. }