You are here

CommentSelection.php in Comment Permissions 8

File

src/Plugin/EntityReferenceSelection/CommentSelection.php
View source
<?php

namespace Drupal\comment_perm\Plugin\EntityReferenceSelection;

use Drupal\comment\CommentInterface;
use Drupal\comment\Plugin\EntityReferenceSelection\CommentSelection as CommentSelectionBase;
use Drupal\comment_perm\CommentAccessTrait;

/**
 * Overrides CommentSelection plugin.
 */
class CommentSelection extends CommentSelectionBase {
  use CommentAccessTrait;

  /**
   * {@inheritdoc}
   */
  protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
    $query = parent::buildEntityQuery($match, $match_operator);

    // Adding the 'comment_access' tag is sadly insufficient for comments:
    // core requires us to also know about the concept of 'published' and
    // 'unpublished'.
    if ($this
      ->userHasAdminPerm()) {

      // Add specific tag to alter query later and remove status condition.
      $query
        ->addTag('comment_perm_access');
    }
    else {
      $query
        ->condition('status', CommentInterface::PUBLISHED);
    }
    return $query;
  }

  /**
   * {@inheritdoc}
   */
  public function validateReferenceableNewEntities(array $entities) {

    // Default selection validation by bundle.
    $entities = array_filter($entities, function ($entity) {
      $target_bundles = $this
        ->getConfiguration()['target_bundles'];
      if (isset($target_bundles)) {
        return in_array($entity
          ->bundle(), $target_bundles);
      }
      return TRUE;
    });

    // Mirror the conditions checked in buildEntityQuery().
    if (!$this
      ->userHasAdminPerm()) {
      $entities = array_filter($entities, function ($comment) {

        /** @var \Drupal\comment\CommentInterface $comment */
        return $comment
          ->isPublished();
      });
    }
    return $entities;
  }

  /**
   * Determine if current use has admin role for at least one comment type.
   *
   * @return bool
   *   TRUE user has administration role, FALSE otherwise.
   */
  protected function userHasAdminPerm() {
    $is_admin = FALSE;
    foreach ($this
      ->getConfiguration()['target_bundles'] as $comment_type) {
      if ($this
        ->accessAdministerComment($this->currentUser, $comment_type)) {
        $is_admin = TRUE;
      }
    }
    return $is_admin;
  }

}

Classes

Namesort descending Description
CommentSelection Overrides CommentSelection plugin.