You are here

public function EntityQueryAlter::alter in Entity API 8

Alters the select query for the given entity type.

Parameters

\Drupal\Core\Database\Query\SelectInterface $query: The select query.

\Drupal\Core\Entity\EntityTypeInterface $entity_type: The entity type.

File

src/QueryAccess/EntityQueryAlter.php, line 95

Class

EntityQueryAlter
Defines a class for altering entity queries.

Namespace

Drupal\entity\QueryAccess

Code

public function alter(SelectInterface $query, EntityTypeInterface $entity_type) {
  if (!$entity_type
    ->hasHandlerClass('query_access')) {
    return;
  }
  $entity_type_id = $entity_type
    ->id();
  $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($query
    ->getMetaData('op') ?: 'view');
  if ($conditions
    ->isAlwaysFalse()) {
    $query
      ->where('1 = 0');
  }
  elseif (count($conditions)) {
    $sql_conditions = $this
      ->mapConditions($conditions, $query);
    $query
      ->condition($sql_conditions);
  }
  $this
    ->applyCacheability(CacheableMetadata::createFromObject($conditions));
}