fa24c3ffe823af6574c11e677aed202e5ba0114f
[yaffs-website] / web / core / modules / comment / src / Plugin / views / field / StatisticsLastCommentName.php
1 <?php
2
3 namespace Drupal\comment\Plugin\views\field;
4
5 use Drupal\user\Entity\User;
6 use Drupal\views\Plugin\views\field\FieldPluginBase;
7 use Drupal\views\ResultRow;
8
9 /**
10  * Field handler to present the name of the last comment poster.
11  *
12  * @ingroup views_field_handlers
13  *
14  * @ViewsField("comment_ces_last_comment_name")
15  */
16 class StatisticsLastCommentName extends FieldPluginBase {
17
18   /**
19    * {@inheritdoc}
20    */
21   public function query() {
22     // last_comment_name only contains data if the user is anonymous. So we
23     // have to join in a specially related user table.
24     $this->ensureMyTable();
25     // join 'users' to this table via vid
26     $definition = [
27       'table' => 'users_field_data',
28       'field' => 'uid',
29       'left_table' => 'comment_entity_statistics',
30       'left_field' => 'last_comment_uid',
31       'extra' => [
32         [
33           'field' => 'uid',
34           'operator' => '!=',
35           'value' => '0'
36         ]
37       ]
38     ];
39     $join = \Drupal::service('plugin.manager.views.join')->createInstance('standard', $definition);
40
41     // nes_user alias so this can work with the sort handler, below.
42     $this->user_table = $this->query->ensureTable('ces_users', $this->relationship, $join);
43
44     $this->field_alias = $this->query->addField(NULL, "COALESCE($this->user_table.name, $this->tableAlias.$this->field)", $this->tableAlias . '_' . $this->field);
45
46     $this->user_field = $this->query->addField($this->user_table, 'name');
47     $this->uid = $this->query->addField($this->tableAlias, 'last_comment_uid');
48   }
49
50   /**
51    * {@inheritdoc}
52    */
53   protected function defineOptions() {
54     $options = parent::defineOptions();
55
56     $options['link_to_user'] = ['default' => TRUE];
57
58     return $options;
59   }
60
61   /**
62    * {@inheritdoc}
63    */
64   public function render(ResultRow $values) {
65     if (!empty($this->options['link_to_user'])) {
66       $account = User::create();
67       $account->name = $this->getValue($values);
68       $account->uid = $values->{$this->uid};
69       $username = [
70         '#theme' => 'username',
71         '#account' => $account,
72       ];
73       return drupal_render($username);
74     }
75     else {
76       return $this->sanitizeValue($this->getValue($values));
77     }
78   }
79
80 }