You are here

public function DisqusCommentCount::render in Disqus 8

Renders the field.

Parameters

\Drupal\views\ResultRow $values: The values retrieved from a single row of a view's query result.

Return value

string|\Drupal\Component\Render\MarkupInterface The rendered output. If the output is safe it will be wrapped in an object that implements MarkupInterface. If it is empty or unsafe it will be a string.

Overrides FieldPluginBase::render

File

src/Plugin/views/field/DisqusCommentCount.php, line 82

Class

DisqusCommentCount
Field handler to present the number of Disqus comments on a node.

Namespace

Drupal\disqus\Plugin\views\field

Code

public function render(ResultRow $values) {

  // Ensure Disqus comments are available on the entity and user has access to
  // edit this entity.
  $entity = $this
    ->getEntity($values);
  if (!$entity) {
    return;
  }
  $field = $this->disqusManager
    ->getFields($entity
    ->getEntityTypeId());
  if (!$entity
    ->hasField(key($field))) {
    return;
  }
  if ($entity
    ->get(key($field))->status && $this->currentUser
    ->hasPermission('view disqus comments')) {

    // Build a renderable array for the link.
    $links['disqus_comments_num'] = [
      'title' => $this
        ->t('Comments'),
      'url' => $entity
        ->toUrl(),
      'fragment' => 'disqus_thread',
      'attributes' => [
        // Identify the node for Disqus with the unique identifier:
        // http://docs.disqus.com/developers/universal/#comment-count
        'data-disqus-identifier' => $entity
          ->get(key($field))->identifier ?: "{$entity->getEntityTypeId()}/{$entity->id()}",
      ],
    ];
    $content = [
      '#theme' => 'links',
      '#links' => $links,
      '#attributes' => [
        'class' => [
          'links',
          'inline',
        ],
      ],
    ];

    // This attaches disqus.js specified in the disqus.libraries.yml file,
    // which will look for the DOM variable disqusComments which is set below.
    // When found, the disqus javascript api replaces the html element with
    // the attribute: "data-disqus-identifier" and replaces the element with
    // the number of comments on the entity.
    $content['#attached']['library'][] = 'disqus/disqus';
    $content['#attached']['drupalSettings']['disqusComments'] = $this->config
      ->get('disqus_domain');
    return $content;
  }
}