NodeNewComments.php 6.41 KB
Newer Older
1
2
3
4
<?php

/**
 * @file
5
 * Contains \Drupal\comment\Plugin\views\field\NodeNewComments.
6
7
 */

8
namespace Drupal\comment\Plugin\views\field;
dawehner's avatar
dawehner committed
9

10
use Drupal\Core\Database\Connection;
11
use Drupal\comment\CommentInterface;
12
use Drupal\Core\Form\FormStateInterface;
13
use Drupal\views\Plugin\views\field\NumericField;
14
use Drupal\views\Plugin\views\display\DisplayPluginBase;
15
use Drupal\views\ResultRow;
16
use Drupal\views\ViewExecutable;
17
use Symfony\Component\DependencyInjection\ContainerInterface;
18
19
20
21
22

/**
 * Field handler to display the number of new comments.
 *
 * @ingroup views_field_handlers
23
 *
24
 * @ViewsField("node_new_comments")
dawehner's avatar
dawehner committed
25
 */
26
class NodeNewComments extends NumericField {
27

28
29
30
31
32
33
34
  /**
   * {@inheritdoc}
   */
  public function usesGroupBy() {
    return FALSE;
  }

35
36
37
38
39
40
41
42
43
44
45
46
47
48
  /**
   * Database Service Object.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $database;

  /**
   * Constructs a Drupal\Component\Plugin\PluginBase object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
49
   * @param mixed $plugin_definition
50
51
52
53
   *   The plugin implementation definition.
   * @param \Drupal\Core\Database\Connection $database
   *   Database Service Object.
   */
54
  public function __construct(array $configuration, $plugin_id, $plugin_definition, Connection $database) {
55
56
57
58
59
60
61
62
    parent::__construct($configuration, $plugin_id, $plugin_definition);

    $this->database = $database;
  }

  /**
   * {@inheritdoc}
   */
63
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
64
65
66
    return new static($configuration, $plugin_id, $plugin_definition, $container->get('database'));
  }

67
  /**
68
   * {@inheritdoc}
69
   */
70
71
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
72

73
    $this->additional_fields['entity_id'] = 'nid';
74
    $this->additional_fields['type'] = 'type';
75
    $this->additional_fields['comment_count'] = array('table' => 'comment_entity_statistics', 'field' => 'comment_count');
76
77
  }

78
79
80
  /**
   * {@inheritdoc}
   */
81
82
  protected function defineOptions() {
    $options = parent::defineOptions();
83

84
    $options['link_to_comment'] = array('default' => TRUE);
85
86
87
88

    return $options;
  }

89
90
91
  /**
   * {@inheritdoc}
   */
92
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
93
    $form['link_to_comment'] = array(
94
95
      '#title' => $this->t('Link this field to new comments'),
      '#description' => $this->t("Enable to override this field's links."),
96
97
98
99
      '#type' => 'checkbox',
      '#default_value' => $this->options['link_to_comment'],
    );

100
    parent::buildOptionsForm($form, $form_state);
101
102
  }

103
104
105
  /**
   * {@inheritdoc}
   */
106
  public function query() {
107
    $this->ensureMyTable();
108
    $this->addAdditionalFields();
109
110
111
    $this->field_alias = $this->table . '_' . $this->field;
  }

112
113
114
  /**
   * {@inheritdoc}
   */
115
  public function preRender(&$values) {
116
    $user = \Drupal::currentUser();
117
    if ($user->isAnonymous() || empty($values)) {
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
      return;
    }

    $nids = array();
    $ids = array();
    foreach ($values as $id => $result) {
      $nids[] = $result->{$this->aliases['nid']};
      $values[$id]->{$this->field_alias} = 0;
      // Create a reference so we can find this record in the values again.
      if (empty($ids[$result->{$this->aliases['nid']}])) {
        $ids[$result->{$this->aliases['nid']}] = array();
      }
      $ids[$result->{$this->aliases['nid']}][] = $id;
    }

    if ($nids) {
134
      $result = $this->database->query("SELECT n.nid, COUNT(c.cid) as num_comments FROM {node} n INNER JOIN {comment_field_data} c ON n.nid = c.entity_id AND c.entity_type = 'node' AND c.default_langcode = 1
135
        LEFT JOIN {history} h ON h.nid = n.nid AND h.uid = :h_uid WHERE n.nid IN ( :nids[] )
136
        AND c.changed > GREATEST(COALESCE(h.timestamp, :timestamp1), :timestamp2) AND c.status = :status GROUP BY n.nid", array(
137
        ':status' => CommentInterface::PUBLISHED,
138
        ':h_uid' => $user->id(),
139
        ':nids[]' => $nids,
140
141
        ':timestamp1' => HISTORY_READ_LIMIT,
        ':timestamp2' => HISTORY_READ_LIMIT,
142
      ));
143
      foreach ($result as $node) {
144
        foreach ($ids[$node->nid] as $id) {
145
146
147
148
149
150
          $values[$id]->{$this->field_alias} = $node->num_comments;
        }
      }
    }
  }

151
152
153
154
155
156
157
158
159
160
161
  /**
   * Prepares the link to the first new comment.
   *
   * @param string $data
   *   The XSS safe string for the link text.
   * @param \Drupal\views\ResultRow $values
   *   The values retrieved from a single row of a view's query result.
   *
   * @return string
   *   Returns a string for the link text.
   */
162
  protected function renderLink($data, ResultRow $values) {
163
    if (!empty($this->options['link_to_comment']) && $data !== NULL && $data !== '') {
164
      $node_type = $this->getValue($values, 'type');
165
      $node = entity_create('node', array(
166
        'nid' => $this->getValue($values, 'nid'),
167
        'type' => $node_type,
168
      ));
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
      // Because there is no support for selecting a specific comment field to
      // reference, we arbitrarily use the first such field name we find.
      // @todo Provide a means for selecting the comment field.
      //   https://www.drupal.org/node/2594201
      $entity_manager = \Drupal::entityManager();
      $field_map = $entity_manager->getFieldMapByFieldType('comment');
      $comment_field_name = 'comment';
      foreach ($field_map['node'] as $field_name => $field_data) {
        foreach ($field_data['bundles'] as $bundle_name) {
          if ($node_type == $bundle_name) {
            $comment_field_name = $field_name;
            break 2;
          }
        }
      }
      $page_number = $entity_manager->getStorage('comment')
        ->getNewCommentPageNumber($this->getValue($values, 'comment_count'), $this->getValue($values), $node, $comment_field_name);
186
      $this->options['alter']['make_link'] = TRUE;
187
      $this->options['alter']['url'] = $node->urlInfo();
188
      $this->options['alter']['query'] = $page_number ? array('page' => $page_number) : NULL;
189
190
191
192
193
194
      $this->options['alter']['fragment'] = 'new';
    }

    return $data;
  }

195
196
197
198
  /**
   * {@inheritdoc}
   */
  public function render(ResultRow $values) {
199
    $value = $this->getValue($values);
200
    if (!empty($value)) {
201
      return $this->renderLink(parent::render($values), $values);
202
203
204
205
206
    }
    else {
      $this->options['alter']['make_link'] = FALSE;
    }
  }
207

208
}