You are here

public function ViewsQueryAlter::alter in Entity API 8

Alters the given views query.

Parameters

\Drupal\views\Plugin\views\query\Sql $query: The views query.

\Drupal\views\ViewExecutable $view: The view.

File

src/QueryAccess/ViewsQueryAlter.php, line 105

Class

ViewsQueryAlter
Defines a class for altering views queries.

Namespace

Drupal\entity\QueryAccess

Code

public function alter(Sql $query, ViewExecutable $view) {
  $table_info = $query
    ->getEntityTableInfo();
  $base_table = reset($table_info);
  if (empty($base_table['entity_type']) || $base_table['relationship_id'] != 'none') {
    return;
  }
  $entity_type_id = $base_table['entity_type'];
  $entity_type = $this->entityTypeManager
    ->getDefinition($entity_type_id);
  if (!$entity_type
    ->hasHandlerClass('query_access')) {
    return;
  }
  $storage = $this->entityTypeManager
    ->getStorage($entity_type_id);
  if (!$storage instanceof SqlContentEntityStorage) {
    return;
  }

  /** @var \Drupal\entity\QueryAccess\QueryAccessHandlerInterface $query_access */
  $query_access = $this->entityTypeManager
    ->getHandler($entity_type_id, 'query_access');
  $conditions = $query_access
    ->getConditions('view');
  if ($conditions
    ->isAlwaysFalse()) {
    $query
      ->addWhereExpression(0, '1 = 0');
  }
  elseif (count($conditions)) {

    // Store the data table, in case mapConditions() needs to join it in.
    $base_table['data_table'] = $entity_type
      ->getDataTable();
    $field_storage_definitions = $this->entityFieldManager
      ->getFieldStorageDefinitions($entity_type_id);

    /** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
    $table_mapping = $storage
      ->getTableMapping();
    $sql_conditions = $this
      ->mapConditions($conditions, $query, $base_table, $field_storage_definitions, $table_mapping);
    $query
      ->addWhere(0, $sql_conditions);
  }
  $this
    ->applyCacheability(CacheableMetadata::createFromObject($conditions));
}