PageRenderTime 31ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

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

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