Commit 7117ae7c authored by git's avatar git Committed by Nikolay Ignatov
Browse files

Issue #3110970 by shaktik, r.spring, timotej-pl, kbrodej, imalabya, bonfil1,...

Issue #3110970 by shaktik, r.spring, timotej-pl, kbrodej, imalabya, bonfil1, drewfranz, humbl_dev, rferguson, benjamincizej, abhijeet.kumar2107, FiNeX, fgm, kiamlaluno, ptt-homme: Remove the code deprecated in Drupal 9
parent 0a308051
Loading
Loading
Loading
Loading
+8 −1
Original line number Diff line number Diff line
<?php

/**
 * @file
 * Elasticsearch connector api.
 */

use Drupal\elasticsearch_connector\Entity\Cluster;

/**
 * @file
 * Hooks provided by the ElasticSearch Connector module.
@@ -13,7 +20,7 @@
 * @param \Drupal\elasticsearch_connector\Entity\Cluster $cluster
 *   Cluster entity.
 */
function hook_elasticsearch_connector_load_library_options_alter(array &$options, \Drupal\elasticsearch_connector\Entity\Cluster $cluster) {
function hook_elasticsearch_connector_load_library_options_alter(array &$options, Cluster $cluster) {
}

/**
+1 −0
Original line number Diff line number Diff line
@@ -3,6 +3,7 @@ name:
description: 
  'Abstraction of making connection to the elasticsearch server. This module is API for a whole bunch of functionality connected with this module.'
core: 8.x
core_version_requirement: ^8 || ^9
package: Elasticsearch
type: module
configure: elasticsearch_connector.config_entity.list
+1 −0
Original line number Diff line number Diff line
@@ -3,6 +3,7 @@ name:
description: 
  'Stand alone module for integration between Drupal Views and Elasticsearch indexes.'
core: 8.x
core_version_requirement: ^8 || ^9
package: Elasticsearch
type: module
dependencies:
+56 −34
Original line number Diff line number Diff line
@@ -68,7 +68,9 @@ class ElasticsearchViewsEntity extends ElasticsearchViewsStandard {
  public function defineOptions() {
    $options = parent::defineOptions();

    $options['display_methods'] = array('default' => array());
    $options['display_methods'] = [
      'default' => [],
    ];

    return $options;
  }
@@ -80,10 +82,10 @@ class ElasticsearchViewsEntity extends ElasticsearchViewsStandard {
    parent::buildOptionsForm($form, $form_state);

    $entity_type_id = $this->getTargetEntityTypeId();
    $view_modes = array();
    $bundles = array();
    $view_modes = [];
    $bundles = [];
    if ($entity_type_id) {
      $bundles = $this->getEntityManager()->getBundleInfo($entity_type_id);
      $bundles = $this->getEntityFieldManager()->getBundleInfo($entity_type_id);
      // In case the field definition specifies the bundles to expect, restrict
      // the displayed bundles to those.
      $settings = $this->getFieldDefinition()->getSettings();
@@ -98,44 +100,44 @@ class ElasticsearchViewsEntity extends ElasticsearchViewsStandard {

    foreach ($bundles as $bundle => $info) {
      $args['@bundle'] = $info['label'];
      $form['display_methods'][$bundle]['display_method'] = array(
      $form['display_methods'][$bundle]['display_method'] = [
        '#type' => 'select',
        '#title' => $this->t('Display for "@bundle" bundle', $args),
        '#options' => array(
        '#options' => [
          '' => $this->t('Hide'),
          'id' => $this->t('Raw ID'),
          'label' => $this->t('Only label'),
        ),
        ],
        '#default_value' => 'label',
      );
      ];
      if (isset($this->options['display_methods'][$bundle]['display_method'])) {
        $form['display_methods'][$bundle]['display_method']['#default_value'] = $this->options['display_methods'][$bundle]['display_method'];
      }
      if (!empty($view_modes[$bundle])) {
        $form['display_methods'][$bundle]['display_method']['#options']['view_mode'] = $this->t('Entity view');
        if (count($view_modes[$bundle]) > 1) {
          $form['display_methods'][$bundle]['view_mode'] = array(
          $form['display_methods'][$bundle]['view_mode'] = [
            '#type' => 'select',
            '#title' => $this->t('View mode for "@bundle" bundle', $args),
            '#options' => $view_modes[$bundle],
            '#states' => array(
              'visible' => array(
                ':input[name="options[display_methods][' . $bundle . '][display_method]"]' => array(
            '#states' => [
              'visible' => [
                ':input[name="options[display_methods][' . $bundle . '][display_method]"]' => [
                  'value' => 'view_mode',
                ),
              ),
            ),
          );
                ],
              ],
            ],
          ];
          if (isset($this->options['display_methods'][$bundle]['view_mode'])) {
            $form['display_methods'][$bundle]['view_mode']['#default_value'] = $this->options['display_methods'][$bundle]['view_mode'];
          }
        }
        else {
          reset($view_modes[$bundle]);
          $form['display_methods'][$bundle]['view_mode'] = array(
          $form['display_methods'][$bundle]['view_mode'] = [
            '#type' => 'value',
            '#value' => key($view_modes[$bundle]),
          );
          ];
        }
      }
      if (count($bundles) == 1) {
@@ -184,7 +186,7 @@ class ElasticsearchViewsEntity extends ElasticsearchViewsStandard {
      if (!empty($row->{$property_path})) {
        foreach ((array) $row->{$property_path} as $j => $value) {
          if (is_scalar($value)) {
            $to_load[$value][] = array($i, $j);
            $to_load[$value][] = [$i, $j];
          }
        }
      }
@@ -194,12 +196,12 @@ class ElasticsearchViewsEntity extends ElasticsearchViewsStandard {
      return;
    }

    $entities = $this->getEntityManager()
    $entities = $this->getEntityFieldManager()
      ->getStorage($this->getTargetEntityTypeId())
      ->loadMultiple(array_keys($to_load));
    $account = $this->getQuery()->getAccessAccount();
    foreach ($entities as $id => $entity) {
      foreach ($to_load[$id] as list($i, $j)) {
      foreach ($to_load[$id] as [$i, $j]) {
        if ($entity->access('view', $account)) {
          $values[$i]->{$property_path}[$j] = $entity;
        }
@@ -208,7 +210,17 @@ class ElasticsearchViewsEntity extends ElasticsearchViewsStandard {
  }

  /**
   * {@inheritdoc}
   * Renders an item.
   *
   * @param $count
   *   Count parameter.
   * @param $item
   *   Item parameter.
   *
   * @return \Drupal\Component\Render\MarkupInterface
   *   Returns rendered item.
   *
   * @throws \Exception
   */
  public function render_item($count, $item) {
    if (is_array($item['value'])) {
@@ -218,12 +230,20 @@ class ElasticsearchViewsEntity extends ElasticsearchViewsStandard {
  }

  /**
   * {@inheritdoc}
   * Gets items.
   *
   * @param \Drupal\views\ResultRow $values
   *   ResultRow parameter.
   *
   * @return array
   *   Returns array of items.
   *
   * @throws \Drupal\Core\Entity\EntityMalformedException
   */
  public function getItems(ResultRow $values) {
    $property_path = $this->getCombinedPropertyPath();
    if (!empty($values->{$property_path})) {
      $items = array();
      $items = [];
      foreach ((array) $values->{$property_path} as $value) {
        if ($value instanceof EntityInterface) {
          $item = $this->getItem($value);
@@ -234,7 +254,7 @@ class ElasticsearchViewsEntity extends ElasticsearchViewsStandard {
      }
      return $items;
    }
    return array();
    return [];
  }

  /**
@@ -247,6 +267,8 @@ class ElasticsearchViewsEntity extends ElasticsearchViewsStandard {
   *   NULL if the entity should not be displayed. Otherwise, an associative
   *   array with at least "value" set, to either a string or a render array,
   *   and possibly also additional alter options.
   *
   * @throws \Drupal\Core\Entity\EntityMalformedException
   */
  protected function getItem(EntityInterface $entity) {
    $bundle = $entity->bundle();
@@ -255,7 +277,7 @@ class ElasticsearchViewsEntity extends ElasticsearchViewsStandard {
    }

    $display_method = $this->options['display_methods'][$bundle]['display_method'];
    if (in_array($display_method, array('id', 'label'))) {
    if (in_array($display_method, ['id', 'label'])) {
      if ($display_method == 'label') {
        $item['value'] = $entity->label();
      }
@@ -272,12 +294,12 @@ class ElasticsearchViewsEntity extends ElasticsearchViewsStandard {
    }

    $view_mode = $this->options['display_methods'][$bundle]['view_mode'];
    $build = $this->getEntityManager()
    $build = $this->getEntityFieldManager()
      ->getViewBuilder($entity->getEntityTypeId())
      ->view($entity, $view_mode);
    return array(
    return [
      'value' => $build,
    );
    ];
  }

}
+77 −60
Original line number Diff line number Diff line
@@ -4,8 +4,8 @@ namespace Drupal\elasticsearch_connector_views\Plugin\views\query;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\elasticsearch_connector\Entity\Cluster;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\join\JoinPluginBase;
use Drupal\views\Plugin\views\query\QueryPluginBase;
use Drupal\views\ResultRow;
use Drupal\views\ViewExecutable;
@@ -47,7 +47,9 @@ class ElasticsearchViewsQuery extends QueryPluginBase {
  protected $index;

  /**
   * @var Cluster
   * The Elastic search cluster.
   *
   * @var \Drupal\elasticsearch_connector\Entity\Cluster
   */
  protected $elasticsearchCluster;

@@ -66,7 +68,7 @@ class ElasticsearchViewsQuery extends QueryPluginBase {
   *
   * @var array
   */
  protected $errors = array();
  protected $errors = [];

  /**
   * Whether to abort the search instead of executing it.
@@ -83,14 +85,14 @@ class ElasticsearchViewsQuery extends QueryPluginBase {
   *
   * @var string[][]
   */
  protected $retrievedProperties = array();
  protected $retrievedProperties = [];

  /**
   * The query's conditions representing the different Views filter groups.
   *
   * @var array
   */
  protected $conditions = array();
  protected $conditions = [];

  /**
   * The conjunction with which multiple filter groups are combined.
@@ -164,7 +166,6 @@ class ElasticsearchViewsQuery extends QueryPluginBase {
    $this->entityTypeManager = $entity_type_manager;
  }


  /**
   * {@inheritdoc}
   */
@@ -185,34 +186,38 @@ class ElasticsearchViewsQuery extends QueryPluginBase {
  }

  /**
   * @param $table
   * Adds a field to list of fields.
   *
   * @param string $table
   *   Table name.
   * @param $field
   * @param string $field
   *   Field name.
   * @param string $alias
   *   Alias.
   * @param array $params
   *   Params array.
   */
  public function addField($table, $field, $alias = '', $params = array()) {
  public function addField($table, $field, $alias = '', array $params = []) {
    $this->fields[$field] = $field;
  }

  /**
   * Ensure a table exists in the queue; if it already exists it won't
   * do anything, but if it does not it will add the table queue. It will ensure
   * a path leads back to the relationship table.
   * Ensures a table exists in the queue.
   *
   * @param $table
   * If it already exists it won't do anything, but if it does not it will add
   * the table queue. It will ensure a path leads back to the relationship
   * table.
   *
   * @param string $table
   *   The not aliased name of the table to ensure.
   * @param $relationship
   * @param string $relationship
   *   The relationship to ensure the table links to. Each relationship will
   *   get a unique instance of the table being added. If not specified,
   *   will be the primary table.
   * @param \Drupal\views\Plugin\views\join\JoinPluginBase $join
   *   A Join object (or derived object) to join the alias in.
   *
   * @return
   * @return null
   *   The alias used to refer to this specific table, or NULL if the table
   *   cannot be ensured.
   */
@@ -225,17 +230,17 @@ class ElasticsearchViewsQuery extends QueryPluginBase {
   * {@inheritdoc}
   */
  public function defineOptions() {
    return parent::defineOptions() + array(
      'bypass_access' => array(
    return parent::defineOptions() + [
      'bypass_access' => [
        'default' => FALSE,
      ),
      'skip_access' => array(
      ],
      'skip_access' => [
        'default' => FALSE,
      ),
      'parse_mode' => array(
      ],
      'parse_mode' => [
        'default' => 'terms',
      ),
    );
      ],
    ];
  }

  /**
@@ -244,33 +249,33 @@ class ElasticsearchViewsQuery extends QueryPluginBase {
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);

    $form['bypass_access'] = array(
    $form['bypass_access'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Bypass access checks'),
      '#description' => $this->t('If the underlying search index has access checks enabled (e.g., through the "Content access" processor), this option allows you to disable them for this view. This will never disable any filters placed on this view.'),
      '#default_value' => $this->options['bypass_access'],
    );
    ];

    if ($this->getEntityTypes(TRUE)) {
      $form['skip_access'] = array(
      $form['skip_access'] = [
        '#type' => 'checkbox',
        '#title' => $this->t('Skip entity access checks'),
        '#description' => $this->t("By default, an additional access check will be executed for each entity returned by the search query. However, since removing results this way will break paging and result counts, it is preferable to configure the view in a way that it will only return accessible results. If you are sure that only accessible results will be returned in the search, or if you want to show results to which the user normally wouldn't have access, you can enable this option to skip those additional access checks. This should be used with care."),
        '#default_value' => $this->options['skip_access'],
        '#weight' => -1,
      );
      ];
      $form['bypass_access']['#states']['visible'][':input[name="query[options][skip_access]"]']['checked'] = TRUE;
    }

    // @todo Move this setting to the argument and filter plugins where it makes
    //   more sense for users.
    $form['parse_mode'] = array(
    $form['parse_mode'] = [
      '#type' => 'select',
      '#title' => $this->t('Parse mode'),
      '#description' => $this->t('Choose how the search keys will be parsed.'),
      '#options' => array(),
      '#options' => [],
      '#default_value' => $this->options['parse_mode'],
    );
    ];

    //    foreach ($this->query->parseModes() as $key => $mode) {
    //      $form['parse_mode']['#options'][$key] = $mode['name'];
@@ -313,7 +318,7 @@ class ElasticsearchViewsQuery extends QueryPluginBase {
    $this->params['fields'] = array_keys($view->field);
    $this->params['fields'][] = '_source';

    $params = array();
    $params = [];

    $params['size'] = $view->pager->getItemsPerPage();
    $params['from'] = $view->pager->getCurrentPage() * $view->pager->getItemsPerPage();
@@ -326,7 +331,7 @@ class ElasticsearchViewsQuery extends QueryPluginBase {

    // Add fields.
    // We are specifying which fields to be visible!
    $params['_source'] = array();
    $params['_source'] = [];
    if (isset($this->params['fields'])) {
      $params['_source'] = array_merge($params['_source'], $this->params['fields']);
    }
@@ -341,7 +346,7 @@ class ElasticsearchViewsQuery extends QueryPluginBase {
      $params['query'] = [
        'bool' => [
          'must' => $boolQueries,
        ]
        ],
      ];
    }

@@ -357,13 +362,16 @@ class ElasticsearchViewsQuery extends QueryPluginBase {
  }

  /**
   * Builds sort array.
   *
   * @return array
   *   Returns array.
   */
  protected function buildSortArray() {
    $sort = array();
    $sort = [];

    foreach ($this->sort_fields as $field => $order) {
      $sort[] = array($field => $order);
      $sort[] = [$field => $order];
    }

    return $sort;
@@ -378,8 +386,8 @@ class ElasticsearchViewsQuery extends QueryPluginBase {
   * @return array
   *   The ready to use filters in Elasticsearch body.
   */
  protected function buildFilterArray($where) {
    $filter = array();
  protected function buildFilterArray(array $where) {
    $filter = [];
    foreach ($where as $wh) {
      foreach ($wh['conditions'] as $cond) {
        $filter[mb_strtolower($wh['type'])][] = $cond['field'];
@@ -387,7 +395,7 @@ class ElasticsearchViewsQuery extends QueryPluginBase {
    }

    if (count($filter) > 1) {
      $filter = array(mb_strtolower($this->group_operator) => $filter);
      $filter = [mb_strtolower($this->group_operator) => $filter];
    }

    return $filter;
@@ -398,10 +406,10 @@ class ElasticsearchViewsQuery extends QueryPluginBase {
   */
  public function alter(ViewExecutable $view) {
    \Drupal::moduleHandler()->invokeAll(
      'views_query_alter', array(
      'views_query_alter', [
        $view,
        $this,
      )
      ]
    );
  }

@@ -409,7 +417,7 @@ class ElasticsearchViewsQuery extends QueryPluginBase {
   * {@inheritdoc}
   */
  public function execute(ViewExecutable $view) {
    $view->result = array();
    $view->result = [];
    $view->total_rows = 0;
    $view->execute_time = 0;

@@ -423,24 +431,23 @@ class ElasticsearchViewsQuery extends QueryPluginBase {
      }

      // Execute the search.
      $response = $client->search(
        array(
      $response = $client->search([
        'index' => $index,
        'body' => $this->query_params,
        )
      )->getRawResponse();
      ])->getRawResponse();

      // Store results.
      if (!empty($response['hits']['hits'])) {
        $item_index = 0;
        foreach ($response['hits']['hits'] as $doc) {
          $result_doc = array();
          $result_doc = [];
          foreach ($doc['_source'] as $field_name => $field_value) {
            if (is_array($field_value)) {
              // TODO: Handle this by implementing the Multivalue interface in D8
              // Handle multivalue with concatenation for now.
              // TODO: Handle this by implementing the Multi-value interface in D8
              // Handle multi-value with concatenation for now.
              $result_doc[$field_name] = implode(' | ', $field_value);
            }else{
            }
            else {
              $result_doc[$field_name] = $field_value;
            }
          }
@@ -471,7 +478,7 @@ class ElasticsearchViewsQuery extends QueryPluginBase {
      foreach ($this->errors as $msg) {
        $this->messenger()->addError($msg);
      }
      $view->result = array();
      $view->result = [];
      $view->total_rows = 0;
      $view->execute_time = 0;
    }
@@ -508,7 +515,7 @@ class ElasticsearchViewsQuery extends QueryPluginBase {
  /**
   * Retrieves the account object to use for access checks for this query.
   *
   * @return \Drupal\Core\Session\AccountInterface|null
   * @return null
   *   The account for which to check access to returned or displayed entities.
   *   Or NULL to use the currently logged-in user.
   */
@@ -535,8 +542,7 @@ class ElasticsearchViewsQuery extends QueryPluginBase {
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    $dependencies = parent::calculateDependencies();
    return $dependencies;
    return parent::calculateDependencies();
  }

  /**
@@ -550,29 +556,40 @@ class ElasticsearchViewsQuery extends QueryPluginBase {
  }

  /**
   * Gets cluster id.
   *
   * @return string
   *   Returns id.
   */
  public function getClusterId() {
    return $this->elasticsearchCluster->cluster_id;
  }

  /**
   * Gets Elasticsearch client.
   *
   * @return \nodespark\DESConnector\ClientInterface
   *   Returns Client interface.
   */
  public function getElasticsearchClient() {
    return $this->elasticsearchClient;
  }

  /**
   * // TODO: Comment.
   * TODO: Comment.
   *
   * @param $table
   * @param string $table
   *   Table name.
   * @param null $field
   *   Field name.
   * @param string $order
   *   Type of order.
   * @param string $alias
   *   Alias paramater.
   * @param array $params
   *   Parameters array.
   */
  public function addOrderBy($table, $field = NULL, $order = 'ASC', $alias = '', $params = array()) {
  public function addOrderBy($table, $field = NULL, $order = 'ASC', $alias = '', array $params = []) {
    // TODO: Implement the addOrderBy method.
  }

Loading