You are here

public function CommentSelection::entityQueryAlter in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/comment/src/Plugin/EntityReferenceSelection/CommentSelection.php \Drupal\comment\Plugin\EntityReferenceSelection\CommentSelection::entityQueryAlter()
  2. 9 core/modules/comment/src/Plugin/EntityReferenceSelection/CommentSelection.php \Drupal\comment\Plugin\EntityReferenceSelection\CommentSelection::entityQueryAlter()

File

core/modules/comment/src/Plugin/EntityReferenceSelection/CommentSelection.php, line 69

Class

CommentSelection
Provides specific access control for the comment entity type.

Namespace

Drupal\comment\Plugin\EntityReferenceSelection

Code

public function entityQueryAlter(SelectInterface $query) {
  parent::entityQueryAlter($query);
  $tables = $query
    ->getTables();
  $data_table = 'comment_field_data';
  if (!isset($tables['comment_field_data']['alias'])) {

    // If no conditions join against the comment data table, it should be
    // joined manually to allow node access processing.
    $query
      ->innerJoin($data_table, NULL, "[base_table].[cid] = [{$data_table}].[cid] AND [{$data_table}].[default_langcode] = 1");
  }

  // Find the host entity type the comment field is on.
  $comment = $this
    ->getConfiguration()['entity'];
  if ($comment) {
    $host_entity_type_id = $comment
      ->getCommentedEntityTypeId();

    /** @var \Drupal\Core\Entity\EntityTypeInterface $host_entity_type */
    $host_entity_type = $this->entityTypeManager
      ->getDefinition($host_entity_type_id);
    $host_entity_field_data_table = $host_entity_type
      ->getDataTable();

    // Not all entities have a data table, so check first.
    if ($host_entity_field_data_table) {
      $id_key = $host_entity_type
        ->getKey('id');

      // The Comment module doesn't implement per-comment access, so it
      // checks instead that the user has access to the host entity.
      $entity_alias = $query
        ->innerJoin($host_entity_field_data_table, 'n', "[%alias].[{$id_key}] = [{$data_table}].[entity_id] AND [{$data_table}].[entity_type] = '{$host_entity_type_id}'");

      // Pass the query to the entity access control.
      $this
        ->reAlterQuery($query, $host_entity_type_id . '_access', $entity_alias);

      // Additional checks for "node" entities.
      if ($host_entity_type_id === 'node') {

        // Passing the query to node_query_node_access_alter() is sadly
        // insufficient for nodes.
        // @see \Drupal\node\Plugin\EntityReferenceSelection\NodeSelection::buildEntityQuery()
        if (!$this->currentUser
          ->hasPermission('bypass node access') && !$this->moduleHandler
          ->hasImplementations('node_grants')) {
          $query
            ->condition($entity_alias . '.status', 1);
        }
      }
    }
  }
}