CommentDefaultFormatter.php 9.28 KB
Newer Older
1
2
3
4
<?php

/**
 * @file
5
 * Contains \Drupal\comment\Plugin\Field\FieldFormatter\CommentDefaultFormatter.
6
7
 */

8
namespace Drupal\comment\Plugin\Field\FieldFormatter;
9

10
use Drupal\comment\CommentManagerInterface;
11
use Drupal\comment\CommentStorageInterface;
12
use Drupal\comment\Entity\Comment;
13
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;
14
use Drupal\Core\Entity\EntityManagerInterface;
15
use Drupal\Core\Entity\EntityViewBuilderInterface;
16
use Drupal\Core\Entity\EntityFormBuilderInterface;
17
use Drupal\Core\Field\FieldItemListInterface;
18
use Drupal\Core\Form\FormStateInterface;
19
use Drupal\Core\Session\AccountInterface;
20
use Drupal\Core\Field\FieldDefinitionInterface;
21
use Drupal\Core\Field\FormatterBase;
22
23
24
25
26
27
28
29
30
31
32
33
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a default comment formatter.
 *
 * @FieldFormatter(
 *   id = "comment_default",
 *   module = "comment",
 *   label = @Translation("Comment list"),
 *   field_types = {
 *     "comment"
34
 *   },
35
 *   quickedit = {
36
 *     "editor" = "disabled"
37
38
39
40
41
 *   }
 * )
 */
class CommentDefaultFormatter extends FormatterBase implements ContainerFactoryPluginInterface {

42
43
44
45
46
47
48
49
50
  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return array(
      'pager_id' => 0,
    ) + parent::defaultSettings();
  }

51
  /**
52
   * The comment storage.
53
   *
54
   * @var \Drupal\comment\CommentStorageInterface
55
   */
56
  protected $storage;
57
58
59
60
61
62
63
64
65
66
67

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * The comment render controller.
   *
68
   * @var \Drupal\Core\Entity\EntityViewBuilderInterface
69
   */
70
  protected $viewBuilder;
71

72
73
74
75
76
77
78
  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface
   */
  protected $entityManager;

79
80
81
82
83
84
85
  /**
   * The entity form builder.
   *
   * @var \Drupal\Core\Entity\EntityFormBuilderInterface
   */
  protected $entityFormBuilder;

86
87
88
  /**
   * {@inheritdoc}
   */
89
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
90
91
92
93
94
95
96
    return new static(
      $plugin_id,
      $plugin_definition,
      $configuration['field_definition'],
      $configuration['settings'],
      $configuration['label'],
      $configuration['view_mode'],
97
      $configuration['third_party_settings'],
98
      $container->get('current_user'),
99
      $container->get('entity.manager'),
100
      $container->get('entity.form_builder')
101
102
103
104
105
106
107
108
    );
  }

  /**
   * Constructs a new CommentDefaultFormatter.
   *
   * @param string $plugin_id
   *   The plugin_id for the formatter.
109
   * @param mixed $plugin_definition
110
   *   The plugin implementation definition.
111
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
112
113
114
115
116
117
118
   *   The definition of the field to which the formatter is associated.
   * @param array $settings
   *   The formatter settings.
   * @param string $label
   *   The formatter label display setting.
   * @param string $view_mode
   *   The view mode.
119
120
   * @param array $third_party_settings
   *   Third party settings.
121
122
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current user.
123
124
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager
125
126
   * @param \Drupal\Core\Entity\EntityFormBuilderInterface $entity_form_builder
   *   The entity form builder.
127
   */
128
  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) {
129
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
130
131
    $this->viewBuilder = $entity_manager->getViewBuilder('comment');
    $this->storage = $entity_manager->getStorage('comment');
132
    $this->currentUser = $current_user;
133
    $this->entityManager = $entity_manager;
134
    $this->entityFormBuilder = $entity_form_builder;
135
136
137
138
139
  }

  /**
   * {@inheritdoc}
   */
140
  public function viewElements(FieldItemListInterface $items) {
141
142
143
    $elements = array();
    $output = array();

144
    $field_name = $this->fieldDefinition->getName();
145
146
147
148
    $entity = $items->getEntity();

    $status = $items->status;

149
    if ($status != CommentItemInterface::HIDDEN && empty($entity->in_preview) &&
150
151
152
153
154
155
156
157
158
159
      // Comments are added to the search results and search index by
      // comment_node_update_index() instead of by this formatter, so don't
      // return anything if the view mode is search_index or search_result.
      !in_array($this->viewMode, array('search_result', 'search_index'))) {
      $comment_settings = $this->getFieldSettings();

      // Only attempt to render comments if the entity has visible comments.
      // Unpublished comments are not included in
      // $entity->get($field_name)->comment_count, but unpublished comments
      // should display if the user is an administrator.
160
      $elements['#cache']['contexts'][] = 'user.roles';
161
162
163
164
165
166
167
168
169
170
171
      if ($this->currentUser->hasPermission('access comments') || $this->currentUser->hasPermission('administer comments')) {
        // This is a listing of Comment entities, so associate its list cache
        // tag for correct invalidation.
        $output['comments']['#cache']['tags'] = $this->entityManager->getDefinition('comment')->getListCacheTags();

        if ($entity->get($field_name)->comment_count || $this->currentUser->hasPermission('administer comments')) {
          $mode = $comment_settings['default_mode'];
          $comments_per_page = $comment_settings['per_page'];
          $comments = $this->storage->loadThread($entity, $field_name, $mode, $comments_per_page, $this->getSetting('pager_id'));
          if ($comments) {
            $build = $this->viewBuilder->viewMultiple($comments);
172
            $build['pager']['#type'] = 'pager';
173
174
175
176
            if ($this->getSetting('pager_id')) {
              $build['pager']['#element'] = $this->getSetting('pager_id');
            }
            $output['comments'] += $build;
177
          }
178
179
180
181
        }
      }

      // Append comment form if the comments are open and the form is set to
182
      // display below the entity. Do not show the form for the print view mode.
183
      if ($status == CommentItemInterface::OPEN && $comment_settings['form_location'] == CommentItemInterface::FORM_BELOW && $this->viewMode != 'print') {
184
        // Only show the add comment form if the user has permission.
185
        $elements['#cache']['contexts'][] = 'user.roles';
186
        if ($this->currentUser->hasPermission('post comments')) {
187
188
189
          // All users in the "anonymous" role can use the same form: it is fine
          // for this form to be stored in the render cache.
          if ($this->currentUser->isAnonymous()) {
190
191
192
193
194
195
196
197
            $comment = $this->storage->create(array(
              'entity_type' => $entity->getEntityTypeId(),
              'entity_id' => $entity->id(),
              'field_name' => $field_name,
              'comment_type' => $this->getFieldSetting('comment_type'),
              'pid' => NULL,
            ));
            $output['comment_form'] = $this->entityFormBuilder->getForm($comment);
198
199
200
201
          }
          // All other users need a user-specific form, which would break the
          // render cache: hence use a #post_render_cache callback.
          else {
202
            $callback = 'comment.post_render_cache:renderForm';
203
204
205
206
            $context = array(
              'entity_type' => $entity->getEntityTypeId(),
              'entity_id' => $entity->id(),
              'field_name' => $field_name,
207
              'comment_type' => $this->getFieldSetting('comment_type'),
208
            );
209
            $placeholder = drupal_render_cache_generate_placeholder($callback, $context);
210
            $output['comment_form'] = array(
211
212
213
214
              '#post_render_cache' => array(
                $callback => array(
                  $context,
                ),
215
              ),
216
              '#markup' => $placeholder,
217
218
            );
          }
219
220
221
222
        }
      }

      $elements[] = $output + array(
223
224
        '#comment_type' => $this->getFieldSetting('comment_type'),
        '#comment_display_mode' => $this->getFieldSetting('default_mode'),
225
226
227
228
229
230
231
232
        'comments' => array(),
        'comment_form' => array(),
      );
    }

    return $elements;
  }

233
234
235
  /**
   * {@inheritdoc}
   */
236
  public function settingsForm(array $form, FormStateInterface $form_state) {
237
238
239
240
241
    $element = array();
    $element['pager_id'] = array(
      '#type' => 'select',
      '#title' => $this->t('Pager ID'),
      '#options' => range(0, 10),
242
      '#default_value' => $this->getSetting('pager_id'),
243
244
245
246
247
248
249
250
251
252
      '#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."),
    );
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    // Only show a summary if we're using a non-standard pager id.
253
    if ($this->getSetting('pager_id')) {
254
      return array($this->t('Pager ID: @id', array(
255
        '@id' => $this->getSetting('pager_id'),
256
257
258
259
260
      )));
    }
    return array();
  }

261
}