You are here

class IndexListBuilder in Search API 8

Builds a listing of search index entities.

Hierarchy

Expanded class hierarchy of IndexListBuilder

1 file declares its use of IndexListBuilder
search_api_db_defaults.install in modules/search_api_db/search_api_db_defaults/search_api_db_defaults.install
Install, update and uninstall functions for the DB Search Defaults module.

File

src/IndexListBuilder.php, line 19

Namespace

Drupal\search_api
View source
class IndexListBuilder extends ConfigEntityListBuilder {

  /**
   * The entity storage class for the 'search_api_server' entity type.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $serverStorage;

  /**
   * Constructs an IndexListBuilder object.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type definition.
   * @param \Drupal\Core\Entity\EntityStorageInterface $storage
   *   The entity storage class.
   * @param \Drupal\Core\Entity\EntityStorageInterface $server_storage
   *   The entity storage class for the 'search_api_server' entity type.
   */
  public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, EntityStorageInterface $server_storage) {
    parent::__construct($entity_type, $storage);
    $this->serverStorage = $server_storage;
  }

  /**
   * {@inheritdoc}
   */
  public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
    return new static($entity_type, $container
      ->get('entity_type.manager')
      ->getStorage($entity_type
      ->id()), $container
      ->get('entity_type.manager')
      ->getStorage('search_api_server'));
  }

  /**
   * Determines whether the "Database Search Defaults" module can be installed.
   *
   * @return \Drupal\Core\StringTranslation\TranslatableMarkup[]
   *   An array of error messages describing why the module cannot be installed,
   *   keyed by a short, machine name-like identifier for the kind of error. If
   *   the array is empty, the module can be installed.
   */
  public static function checkDefaultsModuleCanBeInstalled() {
    $errors = [];

    // If the Node module is missing, no further checks are necessary/possible.
    if (!\Drupal::moduleHandler()
      ->moduleExists('node')) {
      $errors['node_module'] = t('The required Node module is not installed on your site. Database Search Defaults module could not be installed.');
      return $errors;
    }
    $node_types = NodeType::loadMultiple();
    $required_types = [
      'article' => [
        'body',
        'comment',
        'field_tags',
        'field_image',
      ],
      'page' => [
        'body',
      ],
    ];

    /** @var \Drupal\Core\Entity\EntityFieldManager $entity_field_manager */
    $entity_field_manager = \Drupal::service('entity_field.manager');
    foreach ($required_types as $required_type_id => $required_fields) {
      if (!isset($node_types[$required_type_id])) {
        $errors[$required_type_id] = t('Content type @content_type not found. Database Search Defaults module could not be installed.', [
          '@content_type' => $required_type_id,
        ]);
      }
      else {

        // Check if all the fields are here.
        $fields = $entity_field_manager
          ->getFieldDefinitions('node', $required_type_id);
        foreach ($required_fields as $required_field) {
          if (!isset($fields[$required_field])) {
            $errors[$required_type_id . ':' . $required_field] = t('Field @field in content type @node_type not found. Database Search Defaults module could not be installed', [
              '@node_type' => $required_type_id,
              '@field' => $required_field,
            ]);
          }
        }
      }
    }
    if (\Drupal::moduleHandler()
      ->moduleExists('search_api_db')) {
      $entities_to_check = [
        'search_api_index' => 'default_index',
        'search_api_server' => 'default_server',
        'view' => 'search_content',
      ];

      /** @var \Drupal\Core\Entity\EntityTypeManager $entity_type_manager */
      $entity_type_manager = \Drupal::service('entity_type.manager');
      foreach ($entities_to_check as $entity_type => $entity_id) {
        try {

          // Find out if the entity is already in place. If so, fail to install
          // the module.
          $entity_storage = $entity_type_manager
            ->getStorage($entity_type);
          $entity_storage
            ->resetCache();
          $entity = $entity_storage
            ->load($entity_id);
          if ($entity) {
            $errors['defaults_exist'] = t('It looks like the default setup provided by this module already exists on your site. Cannot re-install module.');
            break;
          }
        } catch (PluginException $e) {

          // This can only happen for the view, if the Views module isn't
          // installed. Ignore.
        }
      }
    }
    return $errors;
  }

  /**
   * {@inheritdoc}
   */
  public function getDefaultOperations(EntityInterface $entity) {
    $operations = parent::getDefaultOperations($entity);
    if ($entity instanceof IndexInterface) {
      $route_parameters['search_api_index'] = $entity
        ->id();
      $operations['fields'] = [
        'title' => $this
          ->t('Fields'),
        'weight' => 20,
        'url' => new Url('entity.search_api_index.fields', $route_parameters),
      ];
      $operations['processors'] = [
        'title' => $this
          ->t('Processors'),
        'weight' => 30,
        'url' => new Url('entity.search_api_index.processors', $route_parameters),
      ];
    }
    return $operations;
  }

  /**
   * {@inheritdoc}
   */
  public function buildHeader() {
    return [
      'type' => $this
        ->t('Type'),
      'title' => $this
        ->t('Name'),
      'status' => $this
        ->t('Status'),
    ] + parent::buildHeader();
  }

  /**
   * {@inheritdoc}
   */
  public function buildRow(EntityInterface $entity) {

    /** @var \Drupal\Core\Config\Entity\ConfigEntityInterface $entity */
    $row = parent::buildRow($entity);
    $status = $entity
      ->status();
    $row = [
      'data' => [
        'type' => [
          'data' => $entity instanceof ServerInterface ? $this
            ->t('Server') : $this
            ->t('Index'),
          'class' => [
            'search-api-type',
          ],
        ],
        'title' => [
          'data' => [
            '#type' => 'link',
            '#title' => $entity
              ->label(),
          ] + $entity
            ->toUrl('canonical')
            ->toRenderArray(),
          'class' => [
            'search-api-title',
          ],
        ],
        'status' => [
          'data' => $status ? $this
            ->t('Enabled') : $this
            ->t('Disabled'),
          'class' => [
            'search-api-status',
          ],
        ],
        'operations' => $row['operations'],
      ],
      'title' => $this
        ->t('ID: @name', [
        '@name' => $entity
          ->id(),
      ]),
      'class' => [
        Html::cleanCssIdentifier($entity
          ->getEntityTypeId() . '-' . $entity
          ->id()),
        $status ? 'search-api-list-enabled' : 'search-api-list-disabled',
        $entity instanceof ServerInterface ? 'search-api-list-server' : 'search-api-list-index',
      ],
    ];
    $description = $entity
      ->get('description');
    if ($description) {
      $row['data']['title']['data']['#suffix'] = '<div class="description">' . $description . '</div>';
    }
    if ($status && $entity instanceof ServerInterface && !$entity
      ->isAvailable()) {
      $row['data']['status']['data'] = $this
        ->t('Unavailable');
      $row['class'][] = 'color-error';
    }
    return $row;
  }

  /**
   * {@inheritdoc}
   */
  public function render() {
    $entity_groups = $this
      ->loadGroups();
    $list['#type'] = 'container';
    $list['#attached']['library'][] = 'search_api/drupal.search_api.admin_css';
    $list['servers'] = [
      '#type' => 'table',
      '#header' => $this
        ->buildHeader(),
      '#rows' => [],
      '#empty' => '',
      '#attributes' => [
        'id' => 'search-api-entity-list',
        'class' => [
          'search-api-entity-list',
          'search-api-entity-list--servers-with-indexes',
        ],
      ],
    ];
    foreach ($entity_groups['servers'] as $server_groups) {

      /** @var \Drupal\Core\Config\Entity\ConfigEntityInterface $entity */
      foreach ($server_groups as $entity) {
        $list['servers']['#rows'][$entity
          ->getEntityTypeId() . '.' . $entity
          ->id()] = $this
          ->buildRow($entity);
      }
    }

    // Output the list of indexes without a server separately.
    if (!empty($entity_groups['lone_indexes'])) {
      $list['lone_indexes']['heading']['#markup'] = '<h3>' . $this
        ->t('Indexes not currently associated with any server') . '</h3>';
      $list['lone_indexes']['table'] = [
        '#type' => 'table',
        '#header' => $this
          ->buildHeader(),
        '#rows' => [],
        '#attributes' => [
          'id' => 'search-api-entity-list',
          'class' => [
            'search-api-entity-list',
            'search-api-entity-list--unattached-indexes',
          ],
        ],
      ];
      foreach ($entity_groups['lone_indexes'] as $entity) {
        $list['lone_indexes']['table']['#rows'][$entity
          ->id()] = $this
          ->buildRow($entity);
      }
    }
    elseif (!$list['servers']['#rows']) {
      if (static::checkDefaultsModuleCanBeInstalled() === []) {
        $list['servers']['#empty'] = $this
          ->t('There are no servers or indexes defined. For a quick start, we suggest you install the Database Search Defaults module.');
      }
      else {
        $list['servers']['#empty'] = $this
          ->t('There are no servers or indexes defined.');
      }
    }
    return $list;
  }

  /**
   * Loads search servers and indexes, grouped by servers.
   *
   * @return \Drupal\Core\Config\Entity\ConfigEntityInterface[][]
   *   An associative array with two keys:
   *   - servers: All available search servers, each followed by all search
   *     indexes attached to it.
   *   - lone_indexes: All search indexes that aren't attached to any server.
   */
  public function loadGroups() {
    $indexes = $this->storage
      ->loadMultiple();

    /** @var \Drupal\search_api\ServerInterface[] $servers */
    $servers = $this->serverStorage
      ->loadMultiple();
    $this
      ->sortByStatusThenAlphabetically($indexes);
    $this
      ->sortByStatusThenAlphabetically($servers);
    $server_groups = [];
    foreach ($servers as $server) {
      $server_group = [
        'server.' . $server
          ->id() => $server,
      ];
      foreach ($server
        ->getIndexes() as $index) {
        $server_group['index.' . $index
          ->id()] = $index;

        // Remove this index from $index so it will finally only contain those
        // indexes not belonging to any server.
        unset($indexes[$index
          ->id()]);
      }
      $server_groups['server.' . $server
        ->id()] = $server_group;
    }
    return [
      'servers' => $server_groups,
      'lone_indexes' => $indexes,
    ];
  }

  /**
   * Sorts an array of entities by status and then alphabetically.
   *
   * Will preserve the key/value association of the array.
   *
   * @param \Drupal\Core\Config\Entity\ConfigEntityInterface[] $entities
   *   An array of config entities.
   */
  protected function sortByStatusThenAlphabetically(array &$entities) {
    uasort($entities, function (ConfigEntityInterface $a, ConfigEntityInterface $b) {
      if ($a
        ->status() == $b
        ->status()) {
        return strnatcasecmp($a
          ->label(), $b
          ->label());
      }
      else {
        return $a
          ->status() ? -1 : 1;
      }
    });
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigEntityListBuilder::load public function Loads entities of this type from storage for listing. Overrides EntityListBuilder::load 7
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
EntityHandlerBase::$moduleHandler protected property The module handler to invoke hooks on. 2
EntityHandlerBase::moduleHandler protected function Gets the module handler. 2
EntityHandlerBase::setModuleHandler public function Sets the module handler for this handler.
EntityListBuilder::$entityType protected property Information about the entity type.
EntityListBuilder::$entityTypeId protected property The entity type ID.
EntityListBuilder::$limit protected property The number of entities to list per page, or FALSE to list all entities. 3
EntityListBuilder::$storage protected property The entity storage class. 1
EntityListBuilder::buildOperations public function Builds a renderable list of operation links for the entity. 2
EntityListBuilder::ensureDestination protected function Ensures that a destination is present on the given URL.
EntityListBuilder::getEntityIds protected function Loads entity IDs using a pager sorted by the entity id. 4
EntityListBuilder::getLabel Deprecated protected function Gets the label of an entity.
EntityListBuilder::getOperations public function Provides an array of information to build a list of operation links. Overrides EntityListBuilderInterface::getOperations 2
EntityListBuilder::getStorage public function Gets the entity storage. Overrides EntityListBuilderInterface::getStorage
EntityListBuilder::getTitle protected function Gets the title of the page. 1
IndexListBuilder::$serverStorage protected property The entity storage class for the 'search_api_server' entity type.
IndexListBuilder::buildHeader public function Builds the header row for the entity listing. Overrides EntityListBuilder::buildHeader
IndexListBuilder::buildRow public function Builds a row for an entity in the entity listing. Overrides EntityListBuilder::buildRow
IndexListBuilder::checkDefaultsModuleCanBeInstalled public static function Determines whether the "Database Search Defaults" module can be installed.
IndexListBuilder::createInstance public static function Instantiates a new instance of this entity handler. Overrides EntityListBuilder::createInstance
IndexListBuilder::getDefaultOperations public function Gets this list's default operations. Overrides ConfigEntityListBuilder::getDefaultOperations
IndexListBuilder::loadGroups public function Loads search servers and indexes, grouped by servers.
IndexListBuilder::render public function Builds the entity listing as renderable array for table.html.twig. Overrides EntityListBuilder::render
IndexListBuilder::sortByStatusThenAlphabetically protected function Sorts an array of entities by status and then alphabetically.
IndexListBuilder::__construct public function Constructs an IndexListBuilder object. Overrides EntityListBuilder::__construct
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.