You are here

private function DibaCarousel::getQueriedEntities in Diba carousel slider 8

Use the block settings to query entities.

1 call to DibaCarousel::getQueriedEntities()
DibaCarousel::getItems in src/Plugin/Block/DibaCarousel.php
Get the carousel items.

File

src/Plugin/Block/DibaCarousel.php, line 673

Class

DibaCarousel
Provides a Diba carousel Block.

Namespace

Drupal\diba_carousel\Plugin\Block

Code

private function getQueriedEntities($config) {
  $entities = [];
  $entity_type = !empty($config['entity_selected']) ? $config['entity_selected'] : 'node';

  // Get the storage and init the query builder.
  $storage = $this->entityTypeManager
    ->getStorage($entity_type);
  $query = $storage
    ->getQuery();

  // Filter by content types in nodes.
  if (!empty($config['content_types'])) {

    // Validate that the entity type bundle exists to prevent crash the site
    // when user deletes a content types.
    $bundles = $this
      ->getValidBundles($config['content_types'], $config['entity_selected']);
    $entity_keys = $this->entityTypeManager
      ->getDefinition($entity_type)
      ->get('entity_keys');
    if (!empty($bundles) && isset($entity_keys['bundle'])) {
      $query
        ->condition($entity_keys['bundle'], array_values($bundles), 'IN');
    }
  }

  // Skip content without image.
  if (isset($config['skip_content_without_image']) && TRUE === $config['skip_content_without_image']) {
    if (!empty($config['image'])) {
      $query
        ->condition($config['image'], NULL, 'IS NOT NULL');
    }
  }

  // Filter by publishing options.
  if (!empty($config['publishing_options'])) {
    foreach ($config['publishing_options'] as $key => $value) {
      if (!empty($value)) {

        // Add query condition and filter by publishing option.
        $query
          ->condition($key, 1);
      }
    }
  }

  // Filter by field value.
  if (!empty($config['filter_by_field']) && isset($config['filter_by_field_value'])) {
    $operator = !empty($config['filter_by_field_operator']) ? $config['filter_by_field_operator'] : '=';
    $query
      ->condition($config['filter_by_field'], $config['filter_by_field_value'], $operator);
  }

  // We don't need an order field to order by rand.
  if (isset($config['order_direction']) && 'RANDOM' === $config['order_direction']) {
    $query
      ->addTag('random_order');
  }
  elseif (!empty($config['order_field'])) {
    if ('ASC' === $config['order_direction'] || 'DESC' === $config['order_direction']) {
      $query
        ->sort($config['order_field'], $config['order_direction']);
    }
    else {
      $query
        ->sort($config['order_field']);
    }
  }

  // Limit the query.
  if (!empty($config['limit'])) {
    $query
      ->range(0, $config['limit']);
  }

  // Execute the query and get the IDs.
  $entity_ids = $query
    ->execute();
  if (!empty($entity_ids)) {
    $entities = $storage
      ->loadMultiple($entity_ids);
  }
  return $entities;
}